Tôi có tập lệnh nút bên dưới để về cơ bản sao chép nội dung của một số tệp và chèn chúng vào mongo.Kịch bản nút không bao giờ kết thúc
Tập lệnh không bao giờ có vẻ kết thúc và mặc dù tất cả dữ liệu được chèn thành công, tôi luôn phải thực hiện Ctrl + C để tiêu diệt nó.
Có điều gì mà tôi phải sử dụng trong node.js để kết thúc tập lệnh không?
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]);
});
}
});
});
});
Bạn có thể cần đóng kết nối 'db'. Theo như 'node.js' có thể nói, đó vẫn là một nguồn có thể có của các sự kiện miễn là nó được mở. –
Câu trả lời đúng và các bình luận là chính xác. Về cơ bản bạn cần phải hiểu rằng bạn đang chạy theo "vòng lặp sự kiện" và hậu quả của việc đó là khi bạn mở trình xử lý sự kiện "như bạn có" (ngay cả khi bạn không biết bạn đã làm) thì vòng lặp sẽ chờ sự kiện. Đóng các trình xử lý hoặc rõ ràng "kết thúc vòng lặp" –