nodejs--child_process 创建子进程

child_process

用于创建子进程,允许你在父进程中执行其他程序或脚本。通过这个模块,可以在Node.js中启动和控制子进程、与子进程进行通信等。

常用方法:

1.exec()

用于执行命令并返回标准输出结果。它适用于一次性执行命令并获取结果。

 const { exec } = require('child_process');

   exec('ls', (error, stdout, stderr) => {
     if (error) {
       console.error(`exec error: ${error}`);
       return;
     }
     console.log(`stdout: ${stdout}`);
     console.error(`stderr: ${stderr}`);
   });

2.spawn()

用于启动一个子进程并通过流来交互。适合需要长时间运行的进程或者需要处理大量数据的场景。

const { spawn } = require('child_process');

   const ls = spawn('ls', ['-lh', '/usr']);

   ls.stdout.on('data', (data) => {
     console.log(`stdout: ${data}`);
   });

   ls.stderr.on('data', (data) => {
     console.error(`stderr: ${data}`);
   });

   ls.on('close', (code) => {
     console.log(`child process exited with code ${code}`);
   });

3.fork()

fork()方法是spawn()的一个特殊版本,用于创建一个新的Node.js进程。它适用于Node.js脚本之间的通信。

 const { fork } = require('child_process');

   const child = fork('child.js');

   child.on('message', (message) => {
     console.log('Received message from child:', message);
   });

   child.send({ hello: 'world' });

4.execFile()

适用于执行可执行文件,它比exec()更加高效,因为它不需要通过shell来执行命令。

   const { execFile } = require('child_process');

   execFile('node', ['-v'], (error, stdout, stderr) => {
     if (error) {
       console.error(`execFile error: ${error}`);
       return;
     }
     console.log(`stdout: ${stdout}`);
     console.error(`stderr: ${stderr}`);
   });

重要事件:

  • error:当子进程启动失败时,会触发该事件。
  • exit:子进程终止时触发,包含退出代码。
  • close:当子进程的标准输入、输出、错误流都关闭时触发。

与子进程的通信:
Node.js允许父进程和子进程进行通信,特别是fork()方法,它创建一个父子进程的通信管道。父进程可以通过send()方法向子进程发送消息,子进程可以通过process.on('message')来接收消息。
子进程代码(例如child.js):

process.on('message', (msg) => {
  console.log('Message from parent:', msg);
  process.send({ foo: 'bar' });
});

总结:
child_process模块提供了多种方式来启动、管理和与外部进程进行交互。根据使用场景,可以选择适当的方法,如执行一次性命令使用exec(),处理长时间运行的进程使用spawn(),以及通过fork()进行进程间的消息传递。

posted @ 2025-04-07 10:23  蜗牛般庄  阅读(82)  评论(0)    收藏  举报
Title
页脚 HTML 代码