NodeJS: child_process.exec not executing function
Asked Answered
B

1

9

I'm attempting to do something I think is very simple -- execute an 'echo' line using child_process.exec. My code looks as such:

var exec = require('child_process').exec;

exec('echo "HELLO"', function (error, stdout, stderr) {
    console.log(error);
    console.log(stdout);
    console.log(stderr);
});

As of now, the echo is never being called and neither is the callback. Is there something I'm missing here?

Also, I'm using thins inside a grunt task I'm creating, so I'm not sure if there's anything there that could set it off (though this plugin seems to be doing it fine here --https://github.com/sindresorhus/grunt-shell/blob/master/tasks/shell.js)

Boyt answered 19/6, 2014 at 18:1 Comment(8)
The argument is missing a quote to end the JavaScript string, 'echo "HELLO"'. Is that just in the question? Do you receive any errors? Since it's within a Grunt task, is the task defined to be asynchronous?Sodality
Thanks for catching that -- just in the question. Im not getting any errors. As for the second part, I'm not sure -- I would just like run a command from my task but seem to be getting a bit lost.Boyt
@JonathanLonowski If it's helpful, here is the plugin I'm working on -- github.com/streetlight/grunt-github-changesBoyt
If I run that in NodeJS v0.10.28 it works, displays null and then HELLO and a blank string.Sweatband
That is bizarre -- I'm running 0.10.24. I wonder what has changed since then?Boyt
"Why doesn't my asynchronous task complete?" You'll have to use this.async() and the returned callback within the task or Grunt will interrupt the exec().Sodality
That was totally it! Thank you for catching that!Boyt
@JonathanLonowski if you want to put that comment into an answer, i'd be happy to accept it!Boyt
T
3

Your code is good.

The problem you have is probably about the callback, if you use execSync of child_process it will probably work.

If you want to keep exec function with callback in your grunt task, use this.async();

const done = this.async();
exec('echo "HELLO"', function (error, stdout, stderr) {
    console.log(error);
    console.log(stdout);
    console.log(stderr);
    done();
});

Have a look here: https://gruntjs.com/api/inside-tasks

Truncate answered 17/4, 2021 at 19:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.