简体   繁体   中英

childprocess.spawn or exec shows output via stderr instead of stdout

This code:

const spawn = require('child_process').spawn;
const convert = spawn('convert', ['nda.pdf', 'nda.jpg']);

convert.stdout.on('data', function (data) {
  console.log('stdout: ' + data.toString());
});

convert.stderr.on('data', function (data) {
  console.log('stderr: ' + data.toString());
});

convert.on('exit', function (code) {
  console.log('child process exited with code ' + code.toString());
});

shows this output:

stderr: /tmp/magick-27144xZVKt6FGxrJR1 PNG 2409x3420 2409x3420+0+0 8-bit sRGB 1.027MB 
stderr: 0.150u 0:00.149

stderr: /tmp/magick-27144xZVKt6FGxrJR2 PNG 2409x3423 2409x3423+0+0 8-bit sRGB 4.237MB 0.250u 0:00.260

stderr: /tmp/magick-27144xZVKt6FGxrJR3 PNG 2409x3423 2409x3423+0+0 8-bit sRGB 3.911MB 0.240u 0:00.239

stderr: /tmp/magick-27144xZVKt6FGxrJR4 PNG 2409x3417 2409x3417+0+0 8-bit sRGB 1.241MB 0.190u 0:00.190
...
...
...
stderr: nda.pdf=>Palette-3.jpg[3] PNG 2409x3417 2409x3417+0+0 16-bit sRGB 759KB 11.210u 0:02.369

child process exited with code 0

So it seems that it redirects the output to stderr instead of stdout also everything is ok with the executed command.

The same happens when I use child_process.exec() .

Why does this happen?

I had a similar problem when running a command through Python . The actual problem is with the command itself you are trying to run .To know the output of your command goes to stderr or stdout, do the following:

root@sh> cmd > /tmp/file 

If you see the output of the command going to /tmp/file, then it means the command by default throws its output to stdout .If it doesn't work you can actually see the contents printed on the screen.

Now if you see the contents pasted on your screen,run

root@sh> cmd 2> /tmp/file

Now if the contents move to /tmp/file, it means the command actually throws its usual output to stderr.

Then you can confirm the real problem is not with the language you use but with the way the actual command put its output (either to stderr or stdout) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM