直接上代码
const {spawn}=require('node:child_process');
//为什么是slice(2),因为Nodejs的process.argv输出的第0个是执行程序node.exe,第1个是文件路径,第2个才是参数
const [command,...rest]=process.argv.slice(2);
//返回执行命令和参数,如ls -lh 返回结果是:'ls',['-lh'],当然你也可以执行其它的命令如nodejs的
console.log(command,rest);
//开启子进程spawn()方法
const sp=spawn(command,rest);
let output=[],errorOutput=[];
//子进程的stdin,stdout,stderr都是stream对象中的,不是继承于process主进程
//子进程接收到的数据,添加到数组中
sp.stdout.on('data',(data)=>{output.push(data);
});
//子进程将错误添加到数组中
sp.stderr.on('data',(data)=>{errorOutput.push(data);
});//子进程关闭,输出命令的结果
sp.on('close',(code)=>{const outputstr=code===0?Buffer.concat(output).toString() :Buffer.concat(errorOutput).toString();const printText=outputstr.toString().split(/\r?\n/);console.log('Get the output:\r\n',printText);
});
sp.on('exit',(code)=>{console.log(`child process exited with code ${code}`);
})
如果你要在主进程中输出结果
const { spawn } = require('node:child_process');
const process = require('node:process');
const [command, ...rest] = process.argv.slice(2);console.log(command, rest);//在这里增加stdio:'inherit',表示继承主进程输出
const sp = spawn(command, rest, { stdio: 'inherit' });sp.on('close', (code) => {if (code === 0) {console.log('Command executed successfully');} else {console.log('Command failed with exit code', code);}
});sp.on('exit', (code) => {console.log(`child process exited with code ${code}`);
});
如果用管道模式Pipe形势
const {spawn}=require('node:child_process');
const path=require('node:path');
//这里stdio:[0,'pipe',2]即表示pipe输出
let child=spawn('node',['subchild.js','--port','1337'],{cwd:path.join(__dirname,'test'),stdio:[0,'pipe',2]});
child.stdout.on('data',function(data){console.log(data.toString());
});child.on('close',function(){console.log('child process was closed.');
})
child.on('exit',function(){console.log('child process was exit');
})
//这里是subchild.js
console.log(process.argv);
process.stdout.write('123');
如果使用IPC模式, IPC 的额外通道,允许你在父进程和子进程之间发送和接收消息
const {spawn}=require('node:child_process');
const path=require('node:path');
let child=spawn('node',['ipc.js'],{cwd:path.join(__dirname,'test'),stdio:['ipc']
});
child.on('message',(data)=>{console.log(data);
});
child.send('world');
//ipc.js文件
process.on('message',(message)=>{console.log('接收到父进程信息:',message);process.send({response:'hello form child'});
})
这样就可以在主进程和子进程进行信息的传递