nodejs代码段(四)

child_process以及进程通信

spawn() exec() execFile() fork()

1.spawn()

var spawn = require('child_process').spawn;

var ls_var = spawn('ls',['-lh','/var']);

ls_var.stdout.on('data',function(data){

console.log("stdout:"+data;)

});

2.exec()

var exec = require('child_process').exec;var child = exec('cat 18.js',function(error,stdout,stderr){console.log(stdout);});

3.spawn绑定系统事件

var cp = require('child_process');

var cat = cp.spawn('cat');

cat.stdout.on('data',function(d){

console.log(d.toString());

});

cat.on('exit',function(){

console.log('cat on exit');

});

cat.on('close',function(){

console.log('cat on close');

});

cat.stdin.write('cat on data');

cat.stdin.end();

你可能感兴趣的:(nodejs代码段(四))