Skip to content

Instantly share code, notes, and snippets.

@aduh95
Created October 30, 2018 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aduh95/513d83441d6e124450891a050ea888c2 to your computer and use it in GitHub Desktop.
Save aduh95/513d83441d6e124450891a050ea888c2 to your computer and use it in GitHub Desktop.
const { spawn } = require("child_process");
const { promises: fs } = require("fs");
const path = require("path");
const GUETZLI_EXEC = "C:\\ProgramData\\chocolatey\\bin\\guetzli.EXE";
const MAGICK_EXEC = "C:\\ProgramData\\chocolatey\\bin\\magick.EXE";
// const sizes = [190, 290, 415, 830, 1125];
// const sizes = [612];
const sizes = [317, 830];
const sources = ["*.jpg"];
const promisesCompression = [];
for (const size of sizes) {
const dirPath = path.join(".", size + "w");
promisesCompression.push(
fs
.mkdir(dirPath)
.catch(() =>
fs
.readdir(dirPath)
.then(dir =>
Promise.all(
dir.map(fileName => fs.unlink(path.join(dirPath, fileName)))
)
)
)
.then(
() =>
new Promise((resolve, reject) => {
const childProcess = spawn(MAGICK_EXEC, [
"mogrify",
"-resize",
size,
"-path",
size + "w",
"-format",
"png",
...sources,
]);
childProcess.stdout.pipe(process.stdout);
childProcess.stderr.pipe(process.stderr);
childProcess.on("error", err =>
reject(console.error(size + "w fails", err))
);
childProcess.on("close", errorCode => {
if (errorCode) {
console.error(size + "w fails", errorCode);
reject();
} else {
console.log(size + "w resizing succeeds");
resolve();
}
});
})
)
.then(() => fs.readdir(dirPath))
.then(dir =>
Promise.all(
dir.filter(fileName => fileName.endsWith(".png")).map(
fileName =>
new Promise((resolve, reject) => {
const childProcess = spawn(GUETZLI_EXEC, [
path.join(dirPath, fileName),
path.join(dirPath, fileName.replace(/png$/, "jpg")),
]);
childProcess.stdout.pipe(process.stdout);
childProcess.stderr.pipe(process.stderr);
childProcess.on("error", err =>
reject(console.error(fileName + " " + size + "w fails", err))
);
childProcess.on("close", errorCode => {
if (errorCode) {
console.error(fileName + " " + size + "w fails", errorCode);
reject();
} else {
console.log(fileName + " " + size + "w succeeds");
resolve(Date.now());
}
});
})
)
)
)
.then(all =>
fs
.readdir(dirPath)
.then(dir =>
Promise.all(
dir
.filter(fileName => fileName.endsWith(".png"))
.map(fileName => fs.unlink(path.join(dirPath, fileName)))
).then(() => all)
)
)
);
}
Promise.all(promisesCompression).then(console.log, console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment