您不能使用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