因此,我尝试使用 Nodejs Express FS 模块来迭代我的应用程序中的目录,将每个文件名存储在一个数组中,我可以将其传递到我的 Express 视图并迭代列表,但我很难做到这一点。当我在 files.forEach 函数循环中执行 console.log 时,它打印文件名就很好,但是一旦我尝试执行以下操作:
var myfiles = [];
var fs = require('fs');
fs.readdir('./myfiles/', function (err, files) { if (err) throw err;
files.forEach( function (file) {
myfiles.push(file);
});
});
console.log(myfiles);
它失败了,只记录一个空对象。所以我不确定到底发生了什么,我认为这与回调函数有关,但是如果有人可以引导我了解我做错了什么,以及为什么它不起作用(以及如何使其工作),那就是非常感激。
myfiles 数组为空,因为在调用 console.log() 之前尚未调用回调。
你需要做类似的事情:
var fs = require('fs');
fs.readdir('./myfiles/',function(err,files){
if(err) throw err;
files.forEach(function(file){
// do something with each file HERE!
});
});
// because trying to do something with files here won't work because
// the callback hasn't fired yet.
请记住,节点中的所有事情都是同时发生的,从某种意义上说,除非您在回调中进行处理,否则无法保证异步函数已经完成。
解决这个问题的一种方法是使用 EventEmitter:
var fs=require('fs'),
EventEmitter=require('events').EventEmitter,
filesEE=new EventEmitter(),
myfiles=[];
// this event will be called when all files have been added to myfiles
filesEE.on('files_ready',function(){
console.dir(myfiles);
});
// read all files from current directory
fs.readdir('.',function(err,files){
if(err) throw err;
files.forEach(function(file){
myfiles.push(file);
});
filesEE.emit('files_ready'); // trigger files_ready event
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)