【问题标题】:Node script doesn't ever end节点脚本永远不会结束
【发布时间】:2014-06-06 22:58:16
【问题描述】:

我有下面的节点脚本基本上复制一些文件的内容并将它们插入到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]);

                });
            }

        });
    });
});

【问题讨论】:

  • 您可能需要关闭db 连接。据node.js 所知,只要它是开放的,它仍然是可能的事件来源。
  • 答案正确,cmets 正确。您基本上需要了解您正在“事件循环”下运行,其结果是当您“像您一样”打开事件处理程序时(即使您不知道自己这样做了),那么循环将等待事件。关闭处理程序或明确“结束循环”

标签: javascript node.js mongodb mongoose


【解决方案1】:

您可以拨打process.exit();退出

【讨论】:

  • 但要确保所有同步请求都被完全处理。
  • 不幸的是,这对我在 ECS 容器中不起作用。
【解决方案2】:

一切完成后,致电mongoose.disconnect()。正如@AaronDufour 正确指出的那样,在注册事件处理程序回调时节点不会退出,因为它不知道不会再发生任何事件,例如连接发出“关闭”或“错误”事件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-17
    • 2013-04-09
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2023-04-11
    • 2011-01-20
    相关资源
    最近更新 更多