'use strict';
const glob = require('glob');
const fs = require('fs');
const path = require('path');
const exec = require('child_process').exec;
function run(command) {
var pr = exec(command);
//pr.stdout.pipe(process.stdout);
//pr.stderr.pipe(process.stderr);
pr.stdout.on('data', function (data) {
process.stdout.write(data);
});
pr.stderr.on('data', function (data) {
process.stderr.write(data);
});
}
function optImages(files) {
require('mkdirp').sync('raw');
const rawFolder = path.normalize(process.cwd() + '/raw/');
files.forEach(function (file) {
let filePathParts = path.parse(file);
let rawPath = rawFolder + filePathParts.base;
fs.access(rawPath, function (err) {
if (err) {
let format = filePathParts.ext.substr(1);
if (format == 'png') {
run('@COPY "' + file + '" /B "' + rawPath + '" /B >> nul && @pngquant --force --skip-if-large --speed 1 256 --output "' + file + '" "' + rawPath + '" && @PNGZopfli "' + file + '" 10 "' + file + '" && echo complete: "' + file + '"');
} else if (format == 'jpg' || format == 'jpeg' || format == 'jpe' || format == 'jfif') {
run('@COPY "' + file + '" /B "' + rawPath + '" /B >> nul && @jpegtran -copy none -optimize -progressive "' + rawPath + '" "' + file + '" && echo complete: "' + file + '"');
}
}
});
});
}
if (process.argv.length >= 3) {
optImages(process.argv.slice(2));
} else {
glob(process.cwd() + '/@(*.png|*.jpg|*.jpeg|*.jpe|*.jfif)', function (err, files) {
if (err) {
console.error(err);
process.exit(1);
} else {
if (files.length > 0) {
optImages(files);
}
}
});
}