我正在使用node.js,我試圖讀取一個文件夾並返回file.length,然後我想寫入一個txt文件的值。問題是,當我嘗試使用fs.writeFile時,它會創建一個僅包含世界的文件undefined。使用fs.writeFile時未定義的值
var length;
fs.readdir(dir, function(err, file) {
length = file.length+1;
});
setTimeout(function(){
}, 1000);
fs.writeFile('/public/images/value.txt', length, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
console.log(length);
});
的console.log(長度)返回6
'readdir'和'writeFile'是異步函數。您需要將'fs.writeFile'放入readdir的回調函數中,或者使用promise來解析。問題是'readFile'在'readdir'完成之前被調用,並且不,setTimeout不是一個好的方法來阻止它。 –
以下是關於異步編程的文章,它將幫助您開始使用node.js的異步特性:https://stackoverflow.com/documentation/node.js/8813/asynchronous-programming#t=201706221520109316922 – forrert