Nodejs child_process.exec : Disable printing of stdout on console
Asked Answered
M

4

26

I am performing an image magick identify command via nodejs child_process.exec. and using the string returned from stdout in my script.

Everything works fine but the call prints the stdout msg on console, if the server is not restarted and the console is not cleared for some time, the console becomes messy with stdout messages.

Relevant Code :

var exec = require('child_process').exec;
exec('identify -verbose '+originalFilePath,function(err,stdout,stderr){
    var strOut = stdout;    //  Do something with stdout
});

I just want to disable the printing of the returned result on the console.

Mccusker answered 16/8, 2014 at 14:2 Comment(0)
M
39

In your exact situation, my best solution was to set stdio to 'pipe'. This gives exactly what you'd like.

const execSync = require('child_process').execSync;
try {
  let options = {stdio : 'pipe' };
  let stdout = execSync('echo hello' , options);
  console.log("I got success: " + stdout);
  execSync('rmdir doesntexist' , options);//will exit failure and give stderr
} catch (e) {
  console.error("I got error: " + e.stderr ) ;
}

Result:

I got success: hello
I got error: rmdir: doesntexist: No such file or directory

Notice: Child process is silent

Nothing was printed to console by the child processes themselves, yet we get full stdout and stderr messages to work with.

This is at odds with the documentation* which states that pipe is the default configuration. In reality, setting stdio to pipe changes the behaviour.


* https://nodejs.org/api/child_process.html#child_process_options_stdio

Murcia answered 8/8, 2017 at 21:14 Comment(1)
Confirmed this works / is helpful. Frustrating as you pointed out, how the docs say 'pipe' is default.Vertebra
D
2

Try this:

var exec = require('child_process').exec;
exec('identify -verbose '+originalFilePath, { stdio: ['pipe', 'pipe', 'ignore']}, function(err,stdout,stderr){
    var strOut = stdout;    //  Do something with stdout
});

This ignores the stderr from the exec command but still displays errors and the normal output. See the doc for further configurations.

Desiredesirea answered 24/3, 2016 at 10:41 Comment(0)
L
2
execSync('echo "hello"', { stdio: [] });
Leathery answered 30/4, 2022 at 5:5 Comment(1)
Lovely. Great. So I ended up at execSync(cmd, { stdio: muteParam ? [] : 'pipe', encoding: 'utf8' })...Toname
M
-4

Clearing the console suffices.

process.stdout.write('\033c');    // Clears console
Mccusker answered 16/8, 2014 at 14:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.