Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.