[英]Synchrone issue readdir with singleton in Node.js
First app with Node.js, trying to make a file explore to get contents from them, within a singletoned class, but the order is not that i expected. 第一个使用Node.js的应用程序,试图在一个单例类中探索文件以从中获取内容,但是顺序不是我期望的。 Surely a knowledge missing from me, can you tell me why..
我当然不知道,您能告诉我为什么吗。
Singleton class : 单例课程:
var Singleton = (function()
{
var _instance = null;
return new function()
{
this.Instance = function()
{
if (_instance == null)
{
_instance = new Foo();
}
return _instance;
}
};
})();
The Foo class : 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);
}
};
The calling : 调用:
console.log( Singleton.Instance().method2("myfile") );
In the directory, there is only this myfile.txt 在目录中,只有这个myfile.txt
But, the console displaying me that : 但是,控制台向我显示:
call method1
iterating file0
call constructor
call method2
false
GET /test 304 11ms
myfile
So my response is false and is this normal constructor called at the third position ? 所以我的回答是错误的,这个普通的构造函数是在第三个位置调用的吗? I need the class construct, store, and finally execute the method2().
我需要类构造,存储并最终执行method2()。 What i'm doing bad ?
我在做什么不好?
The root of your problem is that fs.readFile is asynchronous. 问题的根源是fs.readFile是异步的。 method1 returns before you've read the contents of the file.
在读取文件内容之前,method1返回。 A simple fix is to change it to fs.readFileSync .
一个简单的解决方法是将其更改为fs.readFileSync 。
The reason "call constructor" is third is because you invoke method1() first. “调用构造函数”位于第三位的原因是因为您首先调用method1()。
this.method1();
console.log("call constructor");
Everything in method1 gets run before console.log("call constructor") happens. method1中的所有内容都在console.log(“ call构造函数”)发生之前运行。 You can simply swap the two if you want the order to be correct.
如果您希望顺序正确,则可以简单地将两者互换。
From a high-level, using synchronous calls (readdirSync, readFileSync) is usually a bad idea because they block Node from doing anything else while they're running. 从高层来看,使用同步调用(readdirSync,readFileSync)通常是个坏主意,因为它们会阻止Node在运行时执行任何其他操作。 I would recommend studying callbacks, control flow, and the asynchronous nature of Node.js.
我建议研究回调,控制流以及Node.js的异步特性。 There are lots of great tutorials out there.
有很多很棒的教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.