2014-04-22 3 views
6

기본적으로 일부 파일의 내용을 복사하여 몽고에 삽입하는 노드 스크립트가 있습니다.노드 스크립트가 끝나지 않습니다

스크립트가 종료 된 것처럼 보이지 않으며 모든 데이터가 성공적으로 삽입 되더라도 항상 Ctrl + C를 눌러 종료해야합니다.

내가 node.js에서 스크립트를 끝내기 위해 사용해야하는 것이 있습니까?

var mongoose = require('mongoose'); 
mongoose.connect('mongodb://localhost/testdb'); 
var dir = './seeds'; 
var db = mongoose.connection; 

// Show connection error if there is one 
db.on('error', console.error.bind(console, 'Database Connection Error:')); 

// If we successfully connected to mongo 
db.once('open', function callback() { 

    var fs = require('fs'); // Used to get all the files in a directory 

    // Read all the files in the folder 
    fs.readdir(dir, function(err, list) { 

     // Log the error if something went wrong 
     if(err) { 
      console.log('Error: '+err); 
     } 

     // For every file in the list 
     list.forEach(function(file) { 

      // Set the filename without the extension to the variable collection_name 
      var collection_name = file.split(".")[0]; 
      var parsedJSON = require(dir + '/' + file); 

      for(var i = 0; i < parsedJSON.length; i++) { 

       // Counts the number of records in the collection 
       db.collection('cohort').count(function(err, count) { 
        if(err) { 
         console.log(err); 
        } 
       }); 

       db.collection(collection_name).insert(parsedJSON[i], function(err, records) { 

        if(err) { 
         console.log(err); 
        } 

        console.log(records[0]); 
        console.log("Record added as "+records[0]); 

       }); 
      } 

     }); 
    }); 
}); 
+4

'db'연결을 닫아야 할 수도 있습니다. 'node.js '가 알 수있는 한, 그것은 열려있을 때 가능한 이벤트 소스입니다. –

+0

대답이 정확하고 주석이 정확합니다. 기본적으로 "이벤트 루프"에서 실행된다는 것을 이해해야합니다. 그 결과로 "당신이 가진 것처럼"이벤트 핸들러를 열면 루프가 이벤트를 기다립니다. 처리기를 닫거나 명시 적으로 "루프 종료" –

답변

7

모든 것이 완료되면 mongoose.disconnect()으로 전화하십시오. @AaronDufour가 올바르게 지적했듯이 이벤트 핸들러 콜백이 등록되는 동안 노드는 종료되지 않습니다. 예를 들어 'close'또는 'error'이벤트를 발생시키는 연결과 같이 더 이상 예상되는 이벤트가 없다는 것을 모르기 때문입니다.

4

process.exit();을 호출하여 종료 할 수 있습니다.

+0

하지만 모든 동기식 요청이 완전히 처리되었는지 확인하십시오. – zehelvion

관련 문제