Har*_*mer 11 javascript function spawn node.js
在观看我学习Node的在线培训视频中,讲述者说:“对于包含大量数据的较长流程而言,生成更好,而对于短数据则执行效果更好。”
为什么是这样?Node.js中child_process生成和执行函数之间有什么区别,我何时知道要使用哪个?
Pal*_*pad 35
child process created by spawn()
child process created by exec()
-main.js (file)
var {spawn, exec} = require('child_process');
// 'node' is an executable command (can be executed without a shell)
// uses streams to transfer data (spawn.stout)
var spawn = spawn('node', ['module.js']);
spawn.stdout.on('data', function(msg){
console.log(msg.toString())
});
// the 'node module.js' runs in the spawned shell
// transfered data is handled in the callback function
var exec = exec('node module.js', function(err, stdout, stderr){
console.log(stdout);
});
Run Code Online (Sandbox Code Playgroud)
-module.js (baiscally returns a message every second for 5 seconds than exits)
var interval;
interval = setInterval(function(){
console.log( 'module data' );
if(interval._idleStart > 5000) clearInterval(interval);
}, 1000);
Run Code Online (Sandbox Code Playgroud)
spawn()
child process returns the message module data
every 1 second for 5 seconds, because the data is 'streamed' exec()
child process returns one message only module data module data module data module data module data
after 5 seconds (when the process is closed) this is because the data is 'buffered'NOTE that neither the spawn()
nor the exec()
child processes are designed for running node modules, this demo is just for showing the difference, (if you want to run node modules as child processes use the fork()
method instead)
Vas*_*lov 11
主要区别在于spawn
它更适合长时间运行且产量巨大的过程。spawn
通过子进程流输入/输出。exec
缓冲的输出放在一个小的(默认为200K)缓冲区中。而且据我所知,exec
首先生成子外壳,然后尝试执行您的过程。为了避免长话短说spawn
,以防万一您需要从子进程中传输大量数据,并且exec
需要诸如外壳程序管道,重定向之类的功能,甚至需要一次执行多个程序。
一些有用的链接- DZone Hacksparrow
一个很好的起点是NodeJS 文档。
对于“生成”文档状态:
child_process.spawn()方法使用给定命令在args中带有命令行参数来生成新进程。如果省略,则args默认为空数组。
而对于“ exec”:
生成一个shell,然后在该shell中执行命令,缓冲任何生成的输出。传递给exec函数的命令字符串由shell直接处理,特殊字符(基于shell的不同)需要相应地处理。
主要的事情似乎是您是否需要处理命令的输出,我想这可能是影响性能的因素(我没有比较过)。如果只关心流程完成而不是输出,那么“ spawn”就足够了。
归档时间: |
|
查看次数: |
3905 次 |
最近记录: |