您不能使用fs.readdir()返回文件,因为它只是在文件读取完成时异步执行回调。然后,文件对象本身作为参数传递给回调函数。
如果你想返回的readdir的结果,你有两个选择:
1)使用synchronous version of readdir:这将返回文件系统,如你所愿,但是,节点单线程它阻止,直到其完成,这可能会导致您的程序绝对不受欢迎的行为,fi可能是Web应用程序中的一个严重问题(每个客户端的所有请求都将被阻止,直到readdirsync完成)。
2)使用Promise。 Promise实际上不会返回像同步代码这样的值,但可以让您控制异步代码的流程,如同步代码,letting you to throw exceptions and chain return values in your code。
网络,使用使用蓝鸟实现(which requires to install the bluebird package)承诺的一个例子:
var fs = require('fs');
var Promise = require('bluebird');
var dir = '/../../';
var ext = 'yml';
var readdirAsync = Promise.promisify(fs.readdir);
//var c = new Array(); You dont need c as a global now, since you can return the result of the function from inside the iterateOverDir function.
/*Now this function returns a Promise that will pass the readdir value when the promise is fullfilled*/
var test1 = function() {
/*yeah a single line function is pretty redundant but is to keep consistence with the OP code*/
return fs.readdirAsync(dir);
}
/*
and this function just iterates over list performing some actions and
returning a 'result' array. When this whole function is passed as a parameter in a .then(), it takes whatever the function inside the previous then/promise returns, and pass its return value to the next. This is true whenever the previous promise/then is synchronous or asynchronous code.
*/
var iterateOverDir = function(list){
var re = new RegExp("^.*\." + ext + "$");
list.forEach(function(item) {
var result = new Array();
if(re.test(item)) {
result.push(item);
}
return result;
}
test1.then(iterateOverDir).catch(console.log)
then(console.log /* or whatever function that uses the previous function return value.*/);
现在,无极的感谢,你可以管iterateOverDir()首位,而其纯同步代码 - 从简单的每一个值同步代码或异步。但是,您必须将代码保存在.then()。then()...链中。
如果您想要返回一个数组,您可能正在寻找readdir的synchronus版本https://nodejs.org/api/fs.html#fs_fs_readdirsync_path_options –
为什么要从readdir中返回项目?这不会在任何地方被捕获 – Jay