Node.JS中的child_process's execFile中的异步函数
Asynchronous Function in child_process's execFile in Node.JS
在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;
});
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 将函数的上下文应用于javascript变量
- 如何在JavaScript中将字符串转换为函数引用
- 用嵌套函数和默认函数定义函数
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 无法导出函数expressjs/requestjs中的变量
- 函数参数中的数据与指定变量之间的任何性能差异
- JQuery合并了keyup和focusout两个函数
- ES6构造函数返回基类的实例
- 监视函数从服务返回不起作用,但作用域函数起作用
- 我可以在json对象中添加一个函数吗
- AngularJS:我可以跳过函数参数回调吗
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- jquery点击函数select&取消选择
- 拨打'父亲'函数形式a'儿童'ReactJS中的组件
- Node.js v6.2.0类扩展不是函数错误
- 比较从函数和生成的日期对象
- Node.JS中的child_process's execFile中的异步函数
- 如何承诺节点's的child_process.exec和child_proccess.execFile函数与Bl