第一个使用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的异步特性。有很多很棒的教程。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句