[英]Synchrone issue readdir with singleton in Node.js
第一個使用Node.js的應用程序,試圖在一個單例類中探索文件以從中獲取內容,但是順序不是我期望的。 我當然不知道,您能告訴我為什么嗎。
單例課程:
var Singleton = (function()
{
var _instance = null;
return new function()
{
this.Instance = function()
{
if (_instance == null)
{
_instance = new Foo();
}
return _instance;
}
};
})();
Foo類:
var Foo= function Foo()
{
this._filesDir= "./core/files/";
this._storedFiles = {};
this.method1();
console.log("call constructor");
};
Foo.prototype = {
method1: function()
{
console.log("call method1");
var that = this;
var c = 0;
fs.readdirSync(this._filesDir).forEach(function(fileName)
{
console.log("iterating file"+ c);
c++;
fs.readFile(that._filesDir + fileName, 'utf-8', function(err, content)
{
var clean_FileName = fileName.replace(".txt", "");
console.log( clean_fileName );
that._storedFiles[ clean_fileName ] = content;
});
});
},
method2: function( fileName )
{
console.log('call method2');
return ( fileName in this._storedFiles);
}
};
調用:
console.log( Singleton.Instance().method2("myfile") );
在目錄中,只有這個myfile.txt
但是,控制台向我顯示:
call method1
iterating file0
call constructor
call method2
false
GET /test 304 11ms
myfile
所以我的回答是錯誤的,這個普通的構造函數是在第三個位置調用的嗎? 我需要類構造,存儲並最終執行method2()。 我在做什么不好?
問題的根源是fs.readFile是異步的。 在讀取文件內容之前,method1返回。 一個簡單的解決方法是將其更改為fs.readFileSync 。
“調用構造函數”位於第三位的原因是因為您首先調用method1()。
this.method1();
console.log("call constructor");
method1中的所有內容都在console.log(“ call構造函數”)發生之前運行。 如果您希望順序正確,則可以簡單地將兩者互換。
從高層來看,使用同步調用(readdirSync,readFileSync)通常是個壞主意,因為它們會阻止Node在運行時執行任何其他操作。 我建議研究回調,控制流以及Node.js的異步特性。 有很多很棒的教程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.