nodejs利用子进程child_process执行命令及child.stdout输出数据

直接上代码

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'});
})

这样就可以在主进程和子进程进行信息的传递

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值