简体   繁体   English

如何从node.js正确退出

[英]How to exit properly from node.js

The following will read and import many CSV files from disk into MongoDB but NodeJS won't exit after importing all the files if it doesn't go through the resizePhoto() function (Which contains a process.exit after resizing the images). 以下内容将从磁盘读取许多CSV文件并将其导入到MongoDB中,但是如果不通过resizePhoto()函数(在调整图像大小后包含process.exit),则导入所有文件后NodeJS不会退出。

How can I have it to close properly after importing all files without interrupting? 导入所有文件后如何在不中断的情况下正确关闭它? If I add a process.exit .on end it will exit after importing the first file. 如果我添加一个process.exit .on最后,它将在导入第一个文件后退出。

var importData = function(fileName) {

    // Get file from disk.
    var filePath = path.join(folder, fileName);

    // Read and import the CSV file.
    csv.fromPath(filePath, {
        objectMode: true,
        headers: keys
    })
    .on('data', function (data) {

        var Obj = new models[fileName](data);

        models[fileName].find({}).remove().exec();

        Obj.save(function (err, importedObj) {
            if (err) {
                console.log(fileName, err);
            } else if (fileName === 'PHOTOS') {
                resizePhoto(importedObj);
            }
        });

    })
    .on('end', function() {
        console.log(fileName + ': Imported.');
    });
};

module.exports = importData;

Use the module async , method parallel ( https://github.com/caolan/async#parallel ). 使用模块async ,方法parallelhttps://github.com/caolan/async#parallel )。 It can call your tasks (import) in parallel and call the final handler (exit) after all tasks end. 它可以并行调用您的任务(导入),并在所有任务结束后调用最终处理程序(退出)。

In your case: 在您的情况下:
1) Somewhere in project 1)项目中的某个地方

csvImp=require('importData.js');
async.parallel([
    function(done){csvImp(name1,done);},
    function(done){csvImp(name2,done);},
    ...
    function(done){csvImp(nameN,done);}
],
function(err, results){
    process.exit();
});

2) in importData.js 2)在importData.js中

var importData = function(fileName,done) {
...
.on('end', function() {
    console.log(fileName + ': Imported.');
    done();
});

So, next you need to prepare list of tasks. 因此,接下来您需要准备任务列表。 Something like 就像是

names.forEach(function(n){
    tasks.push(function(done){csvImp(n,done);});
});

And call async.parallel with tasks . 并与任务调用async.parallel

Good luck) 祝好运)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM