[英]Node.js with Express: Push to an empty Array returns an empty Array
我列出了/home/myComputer/Desktop/Research
所有目錄中的所有文件,然后使用if語句過濾它們,以僅獲取我想讀取並存儲到數組中的.txt文件。 一切正常,但是將數據推入數組無法正常工作。 當我用控制台登錄它們時,它們不返回任何值[]
。
我嘗試了promise和回調函數,但是它們對我沒有用,因為我不知道如何正確實現它們。
app.get('/jsonData', function(req, res) {
/* Define Arrays */
var theFile = [];
var theCategory = [];
var theContent = [];
var walk = function(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var i = 0;
(function next() {
var file = list[i++];
if (!file) return done(null, results);
file = dir + '/' + file;
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
next();
});
} else {
results.push(file);
next();
}
});
})();
});
};
//walk(process.env.HOME, function(err, results) {
walk("/home/myComputer/Desktop/Research", function(err, results) {
if (err) throw err;
//console.log(results);
results.map(function(val) {
//Get the filename
var fileName = val.match(/[^\/]+$/).join();
//Get the category
var category = val.substr(48).match(/[^\/]+/);
if (fileName == 'written-speech.txt') {
console.log('FOUND!: ' + fileName + ' Category: ' + category) //this works
fs.readFile(val, 'utf8', function(err, contents) {
console.log(contents); // this works
theFile.push(fileName);
theCategory.push(category);
theContent.push(contents);
});
}
})
});
console.log(theFile); // The problem: This returns an empty Array []
console.log(theCategory); // The problem: This returns an empty Array []
console.log(theContent); // The problem: This returns an empty Array []
});
我期望console.log(theFile);
console.log(theCategory);
和console.log(theContent);
返回推入其中的數據。
原因是Javascript中的許多回調都是異步的,這意味着fs.readdir
和fs.readFile
都是異步的,它們的回調不會立即調用,而是稍后調用(請閱讀javascript中的事件循環)。 因此,目前,當您記錄陣列時,它們為空,稍后將向它們推送數據,例如在將來。 為避免這種情況,您可以使用同步方法(fs.readdirSync和fs.readFileSync),該方法很丑陋,如果應用程序有很多其他異步操作,則可能導致性能問題。 如果您的情況只是讀取某些數據的簡單腳本,那可能很好。 另一種首選方法是使用Promise或某個庫來管理回調,例如async
。 如果您對這些概念完全不熟悉,請閱讀一些有關管理異步代碼的文章,例如https://dev.to/mrm8488/from-callbacks-to-fspromises-to-handle-the-file-system-in-nodejs-了解56p2的基本知識並查看一些用例示例。
對於您當前的版本,沒有很多更改就沒有簡單的方法來使其運行。 最好使用我之前描述的概念對其進行重寫。
walk是一個異步函數,因為fs.readdir
是一個異步方法,並且在調用fs.readdir的回調之前,console.log語句正在運行(以同步方式)。
您可以在walk回調的結尾處控制台這些變量的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.