기본적으로 일부 파일의 내용을 복사하여 몽고에 삽입하는 노드 스크립트가 있습니다.노드 스크립트가 끝나지 않습니다
스크립트가 종료 된 것처럼 보이지 않으며 모든 데이터가 성공적으로 삽입 되더라도 항상 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]);
});
}
});
});
});
'db'연결을 닫아야 할 수도 있습니다. 'node.js '가 알 수있는 한, 그것은 열려있을 때 가능한 이벤트 소스입니다. –
대답이 정확하고 주석이 정확합니다. 기본적으로 "이벤트 루프"에서 실행된다는 것을 이해해야합니다. 그 결과로 "당신이 가진 것처럼"이벤트 핸들러를 열면 루프가 이벤트를 기다립니다. 처리기를 닫거나 명시 적으로 "루프 종료" –