节点脚本不会结束

我有下面的节点脚本基本上复制一些文件的内容,并将其插入到mongo。

该脚本似乎永远不会结束,即使所有的数据成功插入,我总是必须做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]); }); } }); }); }); 

当一切完成后,调用mongoose.disconnect() 。 正如@AaronDufour所指出的那样,当事件处理程序callback被注册时,节点不会退出,因为它不知道没有更多的事件会发生,例如发送“closures”或“错误”事件的连接。

你可以调用process.exit(); 退出