使用spawn时,如何正确获取程序输出的进度?
发布于 15小时前 作者 mercury233 110 次浏览 来自 问答

比如,获取ffmpeg的转码进度、获取git push的上传进度 我的思路是直接读stdout/stderr

    var spawn = require('child_process').spawn;
    
    //var proc = spawn("D:\\Program Files\\ffmpeg\\bin\\ffmpeg.exe", ["-y","-i","test.mp4","test.mp3"]);
    var proc = spawn("git", ["push"], { cwd : "../mercury233.github.io/" });
    proc.stdout.setEncoding('utf8');
    proc.stdout.on('data', function(data) {
        console.log('stdout');
        console.log(data);
    });
    proc.stderr.setEncoding('utf8');
    proc.stderr.on('data', function(data) {
        console.log('stderr');
        console.log(data);
    });
    proc.on('close', function (code) {
        console.log('exit ' + code);
    });

测试了一下,两个程序都只会输出到stderr而不是stdout

(前半部分省略)
stderr
size=    2426kB time=00:02:35.22 bitrate= 128.0kbits/s
stderr

stderr
size=    2706kB time=00:02:53.14 bitrate= 128.0kbits/s
stderr
size=    2945kB time=00:03:08.42 bitrate= 128.0kbits/s
stderr
size=    3255kB time=00:03:28.30 bitrate= 128.0kbits/s
stderr
size=    3566kB time=00:03:48.18 bitrate= 128.0kbits/s
stderr
size=    3884kB time=00:04:08.53 bitrate= 128.0kbits/s
stderr
size=    4200kB time=00:04:28.77 bitrate= 128.0kbits/s
stderr
size=    4512kB time=00:04:48.70 bitrate= 128.0kbits/s
stderr

stderr
size=    4722kB time=00:05:02.15 bitrate= 128.0kbits/s
video:0kB audio:4722kB subtitle:0kB other streams:0kB global headers:0kB muxing
overhead:
stderr
0.007156%

exit 0

ffmpeg的输出里有空行

stderr
To https://github.com/mercury233/mercury233.github.io.git
   c80ac3f..49c4205  master -> master

exit 0

而git的输出根本获取不到进度(Writing objects:等)

这样读输出是正确的做法吗? node version v0.12.7 git version 1.9.5.msysgit.1

1 回复

就这么沉了……

回到顶部