var images = require("images"); var fs = require("fs"); var path = "./images"; async function deleteall (path) { var files = []; if(fs.existsSync(path)) { files = fs.readdirSync(path); files.forEach(function(file, index) { var curPath = path + "/" + file; if(fs.statSync(curPath).isDirectory()) { // recurse deleteall(curPath); } else { // delete file fs.unlinkSync(curPath); } }); fs.rmdirSync(path); } }; function explorer(path){ fs.readdir(path, async function(err, files){ if(err){ console.log('error: ' + err); return; } await deleteall('./compressImages') fs.mkdir("./compressImages/",function(err){ if (err) { return console.error(err); } files.forEach(function(file){ fs.stat(path + '/' + file, function(err, stat){ if(err){console.log(err); return;} if(stat.isDirectory()){ explorer(path + '/' + file); }else{ let name = path + '/' + file; let outName = './compressImages'+ '/' +file let width = images(name).width() if(images(name).width()>750){ images(name) .size(750) .save(outName, { quality : 100 }); } else{ images(name) .save(outName, { quality : 40 }); } } }); }); }); }); } explorer(path);