我正在使用async.each
检查180个文件名的数组,使用fs.stat
检查物理文件是否存在。目前,所有文件都存在,但每次调用此代码时,fs.stat
找不到180个图像中的3个不存在。无法找到的图像在每次通话时略有不同。
无法找到的第一个图像总是在数组中的第70个文件名周围。如果我将数组的大小减小到(例如)50个名称的列表,则会找到所有图像。
// ImagesToCheck is an array of 180 filepaths, all of which exist on the server
var index = 0
async.each(ImagesToCheck,
function(item, cb) {
fs.stat(item, function(error, value) {
if (error) {
// Logs "ENOENT: no such file or directory"
console.log("error is "+error)
// this is logging the correct filename, which DOES exist
console.log("filename is "+ImagesToCheck[index])
Speakers[index].speaker_image_url = null
index++
cb()
}
else {
// Image exists
// console.log("image exists " + index)
Speakers[index].speaker_image_url = "http://www.apiurl.co.uk/images/seminar_image-" + rows[index].seminar_id + ".jpg"
index++
cb()
}
}) // close fs.stat
},
function(err) {
// sends the array of URLs
callBack(Speakers)
})
//现在使用fs.open而不是fs.stat,使用async.forEachOf,并获得基本相同的结果:
var index = 0
async.forEachOf(ImagesToCheck,
function(item, key, cb) {
fs.open(item, 'r', function(error, value) {
if (error) {
// Logs "ENOENT: no such file or directory"
console.log("error is " + error)
// this is logging the correct filename, which DOES exist
console.log("index is " + index + ", filename is " + ImagesToCheck[index])
Speakers[index].speaker_image_url = null
index++
return cb()
}
// if no error
Speakers[index].speaker_image_url = "http://www.apiurl.co.uk/images/seminar_image-" + rows[index].seminar_id + ".jpg"
index++
cb()
})
},
function(err) {
// send the array of urls
callBack(Speakers)
}
)
答案 0 :(得分:0)
注意:这只是为了展示测试实现。这不是一个答案
刚尝试在名为'use strict';
const fs = require('fs'),
async = require('async');
let files = [],
results = [],
i = 0;
while(i < 200) {
files.push('./files/' + i + '.txt');
i = i + 1;
}
async.eachOf(files, (file, i, callback) => {
fs.stat(file, (err, stats) => {
files[i] = !err;
callback();
});
}, () => {
let notFound = files.filter((f) => {
return !f;
});
console.log('fs.stat didn\'t found ' + notFound.length + '/200 files');
files.map((f, i) => {
if(!f) {
console.log('File ' + i + ' wasn\'t found');
}
})
});
的文件夹中生成200个文件(0.txt,1.txt ... 200.txt),并尝试了以下代码:
fs.stat
未发现错误,似乎问题不是rvm use system