尝试运行一个脚本,以异步方式打开一堆文件并读取其内容。我收到一个错误,其中fs.readFile
的回调没有数据,但文件在那里,并且当前没有被其他任何东西打开。完全糊涂了。
错误是:
错误:好的,打开 'd:\工作区\的FastTrack \公共\ cloudmade \图像\ 998 \ 256 \ 6 \ 31 \ 61.png'
更多信息:
程序运行一个循环,其中有一堆对象,如下所示:
newObject = {
filePath:filePath,
scanPixels:function(parent){
....
}
}
循环调用每个对象的scanPixels
函数,然后在fs.readFile
上执行parent.filePath
这是for循环
for(var index=0;index<objects.length;index++){
objects[index].scanPixels(objects[index]);
}
scanPixels函数基本上是这样的:
scanPixels:function(parent){
png_js.decode(parent.filePath, function(pixels){
...more stuff
在png_js文件中:
PNG.decode = function(path, fn) {
return fs.readFile(path, function(err, file) {
var png;
png = new PNG(file);
return png.decode(function(pixels) {
return fn(pixels);
});
});
};
答案 0 :(得分:1)
问题是fs.readFile不返回值。你会想要fs.readFileSync
var buffer1 = fs.fileReadSync('./hello1.txt');
var buffer2;
fs.fileRead('./hello2.txt', function (err, file) {
buffer = file;
});