2014-01-26 2 views
0

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() 실행이 필요합니다. 내가 뭘하고 있는거야?

답변

1

문제의 근본 원인은 fs.readFile이 비동기 적이라는 것입니다. method1은 파일 내용을 읽기 전에 반환됩니다. 간단한 수정은 fs.readFileSync으로 변경하는 것입니다.

"call constructor"이 3 인 이유는 먼저 method1()을 호출하기 때문입니다.

this.method1(); 
console.log("call constructor"); 

console.log ("call constructor")가 발생하기 전에 method1의 모든 항목이 실행됩니다. 순서를 올바르게하려면 두 가지를 바꿀 수 있습니다.

높은 수준에서 동기 호출 (readdirSync, readFileSync)을 사용하면 일반적으로 Node가 실행 중에 다른 작업을 수행하지 못하도록 차단하므로 나쁜 생각입니다. 콜백, 제어 흐름 및 Node.js의 비동기 특성을 연구하는 것이 좋습니다. 많은 훌륭한 튜토리얼이 있습니다.

+0

그게 전부입니다. 개념 문제에 관해서, 나는 this.method1()을 소트했다. 생성자에서 단순히 응용 프로그램의 주요 시작 부분에서 호출하는 동안 나는 readdirSync를 마지막으로 readdir로 편집했습니다. 감사 – Flozza

관련 문제