Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node Child Process Exec Command Failed with error code 1

I am trying to execute some line using node js child process and getting error. Following is my code:

let cmd : string = "code " + PROJECTS[value];
exec(cmd, function callback(error, stdout, stderr) {
  console.log("started console app");
});

ERROR :

cmd:"C:\WINDOWS\system32\cmd.exe /s /c "code c:\Users\shana\Dropbox\code-settings-syn... (length: 82)"
code:1
killed:false
message:"Command failed: C:\WINDOWS\system32\cmd.exe /s /c "code c:\Users\shana\Dropbox\c... (length: 99)"
signal:null
stack:undefined

Detail of error JSON.

Full CMD : "C:\WINDOWS\system32\cmd.exe /s /c "code c:\Users\shana\Dropbox\code-settings-sync""
Full message : "Command failed: C:\WINDOWS\system32\cmd.exe /s /c "code c:\Users\shana\Dropbox\code-settings-sync"\n"
like image 207
Shan Khan Avatar asked Jan 05 '16 22:01

Shan Khan


People also ask

What is exec in node JS?

The exec() function in Node. js creates a new shell process and executes a command in that shell. The output of the command is kept in a buffer in memory, which you can accept via a callback function passed into exec() .

What is child_process spawn?

child_process. exec() : spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete. child_process. execFile() : similar to child_process. exec() except that it spawns the command directly without first spawning a shell by default.

How do I run an external program from node JS?

To execute an external program from within Node. js, we can use the child_process module's exec method. const { exec } = require('child_process'); exec(command, (error, stdout, stderr) => { console. log(error, stdout, stderr) });


2 Answers

try a simpler example ..

var exec = require('child_process').exec;
var cmd = 'code C:\Program Files';
exec(cmd, function(err, stdout, stderr) {
if (err) {
console.error(err);
return;
}
console.log(stdout); 
});

does this work??

like image 145
Nabeel Hassan Avatar answered Sep 18 '22 06:09

Nabeel Hassan


I didn't want to see the whole error (too verbose) so I did something like this:

try { 
  const { stdout, stderr } = await exec('echo TEST');
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
} catch (e) {
  // If exec fails and you want to see the whole ugly error: 
  // console.error(e);
  console.log('How about a nice human readable message instead?'); 
}

Because of the "await" this goes inside an "async" function. More information: https://stackoverflow.com/a/56095793/722796

like image 30
PJ Brunet Avatar answered Sep 20 '22 06:09

PJ Brunet