'close' 事件


  • code <number> 如果子进程自己退出,则为退出码。
  • signal <string> 终止子进程的信号。

在进程已结束并且子进程的标准输入输出流已关闭之后,则触发 'close' 事件。 这与 'exit' 事件不同,因为多个进程可能共享相同的标准输入输出流。 'close' 事件将始终在 'exit''error'(如果子进程衍生失败)已经触发之后触发。

const { spawn } = require('node:child_process');
const ls = spawn('ls', ['-lh', '/usr']);

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

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

ls.on('exit', (code) => {
  console.log(`child process exited with code ${code}`);
});
  • code <number> The exit code if the child exited on its own.
  • signal <string> The signal by which the child process was terminated.

The 'close' event is emitted after a process has ended and the stdio streams of a child process have been closed. This is distinct from the 'exit' event, since multiple processes might share the same stdio streams. The 'close' event will always emit after 'exit' was already emitted, or 'error' if the child failed to spawn.

const { spawn } = require('node:child_process');
const ls = spawn('ls', ['-lh', '/usr']);

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

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

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