Node.js의 첫 번째 앱으로 싱글 톤 클래스 내에서 내용을 가져올 수 있도록 파일을 탐색하려고하지만 예상 한 순서가 아닙니다.Synchrone이 node.js에서 싱글 톤을 사용하여 readdir을 실행합니다.
var Singleton = (function()
{
var _instance = null;
return new function()
{
this.Instance = function()
{
if (_instance == null)
{
_instance = new Foo();
}
return _instance;
}
};
})();
푸 클래스 :
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() 실행이 필요합니다. 내가 뭘하고 있는거야?
그게 전부입니다. 개념 문제에 관해서, 나는 this.method1()을 소트했다. 생성자에서 단순히 응용 프로그램의 주요 시작 부분에서 호출하는 동안 나는 readdirSync를 마지막으로 readdir로 편집했습니다. 감사 – Flozza