tomgp
9/27/2017 - 1:54 PM

convert a bunch of files using nodejs and the sips utility on osx

convert a bunch of files using nodejs and the sips utility on osx

const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');
const root = './';

const sizes = {
    s:300,
    m:600,
    l:1200,
};

const getImages = (filePath) => {
    let isImage = false;
    ['png','gif','jpg'].forEach((ext)=>{
        isImage = (path.extname(filePath).indexOf(ext) >= 0) || isImage;
    });
    return isImage;
}

const getDirectories = (filePath) => {
    return fs.lstatSync(filePath).isDirectory()
}

const imageResize = (imagePath, outputPath, sizes) => {
    Object.entries(sizes).forEach(([key, value])=>{
        const outFile = path.join(outputPath, key, path.parse(imagePath).base);
        const sips = spawn('sips', [imagePath, '-Z', value, '--out', outFile]);

        sips.stdout.on('data', (data) => {
            console.log(`converting... ${data}`);
        });
        
        sips.stderr.on('data', (data) => {
            console.log(`ERROR: ${data}`);
        });
        
        sips.on('close', (code) => {
            console.log(`finished ${outFile}. exit code ${code}`);
        });
    })
}

const sourceDirs = fs.readdirSync(root).filter(getDirectories);

sourceDirs.forEach((str) => {
    const subpath = path.join(root, str);

    Object.keys(sizes).forEach((key)=>{
        //check / create output directories
        const dirName = path.join(subpath, key)
        if (!fs.existsSync( dirName )){
            fs.mkdirSync( dirName );
        }
    });
    
    fs.readdirSync(subpath)
        .filter(getImages)
        .map((imageFile) => {
            return path.join(subpath, imageFile)
        })
        .forEach((imagePath)=>{
            imageResize(imagePath, subpath, sizes);
        });
    
});