Node.JS中的child_process's execFile中的异步函数

Asynchronous Function in child_process's execFile in Node.JS

本文关键字:execFile 函数 异步 中的 JS child process Node      更新时间:2023-09-26

在node.js (casperJS脚本)文件中,child_process模块中的execFile函数用于运行脚本mongoScript.js访问Mongodb的数据库集合。

execFile("node", 'mongoScript.js', null, function (err, stdout, stderr) {
    console.log("execFileSTDOUT:", stdout);
    console.log("execFileSTDERR:", JSON.stringify(stderr));
    finished = true;
});

其中mongoScript.js包含async函数collection.find

var mongojs = require('mongojs')
var db = mongojs()
var collection = db.collection('myCollection')
collection.find({}, function(err, docs) {       
    console.log('done')
    db.close()
})

问题:似乎在collection.find更改打印done之前退出了脚本。我们如何让它等待collection.find完成运行?

如文档所述,execFile函数的args参数应该是一个数组:

execFile("node", ['mongoScript.js'], null, function (err, stdout, stderr) {
    console.log("execFileSTDOUT:", stdout);
    console.log("execFileSTDERR:", JSON.stringify(stderr));
    finished = true;
});

如果它不是一个数组,JavaScript可能会尝试将字符串分割成一个数组,在这种情况下node m o n g o ...实际上被调用。

try this

exec("node mongoScript.js"+childArgs,function (err, stdout, stderr) {
    console.log("execFileSTDOUT:", stdout);
    console.log("execFileSTDERR:", JSON.stringify(stderr));
    finished = true;
});