我陷入了nodejs异步的问题。 我想调整文件夹中的图像大小,resize
是一个可执行的二进制文件。 问题是我的resize
不能同时执行多次。以便我使用Array.prototype.forEach而不是async.forEach来期望每个文件都将被逐个处理。让exec函数里面forEach做一个一个的
var exec = require('child_process').exec;
exec('ls ' + IMAGE_FOLDER, function (error, stdout, stderr) {
if (error) {throw error;}
var fileList = stdout.split("\n");
fileList.pop(); //Remove the last element that null
fileList.forEach(function(imageFile, index, array) {
var inFile = IMAGE_FOLDER + imageFile;
console.log(inFile);
exec('resize ' + inFile, function(err, stdout, stderr){
if (err) {
console.log(stderr);
throw err;
}
console.log('resized ' + imageFile);
})
});
});
但我得到的结果是我的代码的行为是无块,它打印出:
image1
image2
...
resized image1
resized image2
...
我预期的打印输出的行为应该是:
image1
resize image1
image2
resize image2
...
请告诉我我错在哪里。任何帮助是不同的欣赏。
您是否找到解决方案?如果是,请张贴您的答案 –
我做了替代解决方案,但我认为您可以尝试Jyotman Singh的以下建议。如果它有效,请留言。 –