通过 nodejs spawn 执行 wget 命令时动态进度条无法在控制台正常打印要如何解决?

hi everybody.

我通过 node.js 编写了一段类似下述的代码,使用 child_process.spawn 创建子进程执行 wget 命令,同时将标准 io 定向到 node.js 主进程的标准 io

let cp = spawn('wget', 'some_file_url')
cp.stdin.pipe(process.stdin)
cp.stdout.pipe(process.stdout)
cp.stderr.pipe(process.stderr)

然后在 node.js 执行上述代码时,一切显示都很正常,除了进度条外 🥶 它不是动态变化的,而是一行一行持续叠加输出的

     0K .......... .......... .......... .......... ..........  0%  134K 5m21s
    50K .......... .......... .......... .......... ..........  0%  631K 3m14s
   100K .......... .......... .......... .......... ..........  0% 4.64M 2m12s
   150K .......... .......... .......... .......... ..........  0%  167M 99s

正常来说,如果我通过终端执行 wget

$ wget some_file_url

会显示一个动态变化的进度条

file.tar.gz                  15%[======>                                         ]   6.69M  2.27MB/s

请教各位大佬,我要怎么改动才能让进度条的打印与正常在终端执行一致呢?

相关环境信息

  • node.js: v14.16.1
  • wget: GNU Wget 1.21.2 built on darwin21.1.0
阅读 2.5k
1 个回答

自己解决了,问题原因与 node.js 无关。

查手册发现 wget 进度条有两种模式 bar or dot

叠加输出的其实就是 dot 模式,加上 --progress=bar 即可。不过仅仅这样还不够,man wget 文档里有一行

When the output is not a TTY, the progress bar always falls back to "dot", even if --progress=bar was passed to Wget during invocation. This behaviour can be overridden and the "bar" output forced by using the "force" parameter as --progress=bar:force

而通过 spawn 执行命令时会被 wget 认定为非 TTY 环境,所以应该是 --progress=bar:force 才生效

修改后的完整代码示例如下

// foo.js
const {spawn} = require('child_process')

let cp = spawn('wget', ['https://www.baidu.com', '--progress', 'bar:force'])
cp.stdin.pipe(process.stdin)
cp.stdout.pipe(process.stdout)
cp.stderr.pipe(process.stderr)
$ node foo.js
--2022-03-02 18:41:50--  https://www.baidu.com/
Resolving www.baidu.com (www.baidu.com)... 112.80.248.76
Connecting to www.baidu.com (www.baidu.com)|112.80.248.76|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2443 (2.4K) [text/html]
Saving to: ‘index.html’

index.html          100%[===================>]   2.39K  --.-KB/s    in 0s      

2022-03-02 18:41:50 (11.9 MB/s) - ‘index.html’ saved [2443/2443]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题