更新标准输出的子进程事件

Child process event for updated stdout

目前我的代码生成了 7zip。当您通常调用 7zip cli 时,它会显示一条进度消息,该消息会随着它的进行而更新:

> 7z u archive.7z dir 

7-Zip 19.00 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2019-02-21

Scanning the drive:
14 folders, 37 files, 45418359 bytes (44 MiB)
...

// this part gets updated
22% 7 + dir/image.png

我的代码当前正确记录标准输出,但未记录更新:

const child = spawn('7z', ['u', 'archive.7z', 'dir'], { shell: true });
child.stdout.on("data", data => console.log("" + data));

我注意到记录静态内容后 child.stdout 会调用事件 resume 和 readable,但仍然不知道在那之后要做什么。

您需要使用以下标志分别将进度的输出流设置为 stdoutstderr

-bs{o|e|p}{0|1|2} : set output stream for output/error/progress line

// File: main.js
const { spawn } = require('child_process');
const child = spawn('7z', ['u', '-bsp1', 'archive.7z', 'dir']);
// -bsp1 = stdout
child.stdout.on('data', data => console.log(data.toString()));
// -bsp2 = stderr
// child.stderr.on('data', data => console.log(data.toString()));
$ node main.js 

7-Zip (a) [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=C.UTF-8,Utf16=on,HugeFiles=on,64 bits,4 CPUs Intel(R) Core(TM) i7-4790K CPU @ 4.00GHz (306C3),ASM,AES-NI)

Scanning the drive:
1 folder, 1 file, 2877227008 bytes (2744 MiB)

Creating archive: archive.7z

Items to compress: 2

  0%
  0% + dir/ubuntu-20.04.2.0-desktop-amd64.iso
  1% + dir/ubuntu-20.04.2.0-desktop-amd64.iso
  2% + dir/ubuntu-20.04.2.0-desktop-amd64.iso
  3% + dir/ubuntu-20.04.2.0-desktop-amd64.iso
  4% + dir/ubuntu-20.04.2.0-desktop-amd64.iso