Node.js Spawn 显示 STDOUT 实时无法工作

问题描述 投票:0回答:2

我有一个应用程序,它接收文件链接并下载它们,为了下载,我使用 aria2c。

为了首先执行此操作,我使用了

exec
,但由于我想获取下载进度,所以我使用了
spawn

这是我使用 aria2c 下载文件的代码:

'use strict';

const
    spawn = require( 'child_process' ).spawn,
    aria2c = spawn( 'aria2c', ['-x8', 'https://wa-us-ping.vultr.com/vultr.com.100MB.bin' ] );

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

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

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

当我运行此代码时,它不会将 aria2c 输出打印到标准输出,它仅在下载完成时显示它。

我想知道如何解决这个问题。

node.js spawn
2个回答
1
投票

我不太了解

aria2c
,但这就是我想到的:

// enable a specific log level
aria2c = spawn( 'aria2c', ['--log-level=info', '-l-', '-x8', 'https://wa-us-ping.vultr.com/vultr.com.100MB.bin' ]);

// find the percentage (this is not well-tested...)
aria2c.stdout.on( 'data', data => {
  data = data.toString();
  if (/ETA:/.test(data)) {
    let pct = data.match(/\(.*?%\)/)[0];
    console.log( `stdout: ${ pct }` );
  }
});

(其余代码保持不变)

您无法(轻松)捕获默认输出的原因是因为进度行仅以回车符结束,而不是换行符,这会导致这些行被缓冲,并且最终会出现一个

data
事件在包含所有这些行的末尾。

通过更改日志级别,进度行会散布在其他行中,这将使缓冲区更快填满,或导致更多 I/O 刷新,从而更频繁地触发

data
事件,从而允许您捕获进度数据.


0
投票

--摘要间隔=SEC

设置输出下载进度摘要的时间间隔(以秒为单位)。

设置 0 抑制输出。默认值:60

https://aria2.github.io/manual/en/html/aria2c.html#cmdoption-summary-interval

© www.soinside.com 2019 - 2024. All rights reserved.