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)

streetlight
  • 5,968
  • 13
  • 62
  • 101
  • 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? – Jonathan Lonowski Jun 19 '14 at 18:03
  • 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. – streetlight Jun 19 '14 at 18:09
  • @JonathanLonowski If it's helpful, here is the plugin I'm working on -- https://github.com/streetlight/grunt-github-changes – streetlight Jun 19 '14 at 18:15
  • If I run that in NodeJS v0.10.28 it works, displays `null` and then `HELLO` and a blank string. – tadman Jun 19 '14 at 18:25
  • That is bizarre -- I'm running 0.10.24. I wonder what has changed since then? – streetlight Jun 19 '14 at 18:29
  • 4
    "[Why doesn't my asynchronous task complete?](http://gruntjs.com/creating-tasks#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()`. – Jonathan Lonowski Jun 19 '14 at 18:31
  • That was totally it! Thank you for catching that! – streetlight Jun 19 '14 at 18:40
  • @JonathanLonowski if you want to put that comment into an answer, i'd be happy to accept it! – streetlight Jun 27 '14 at 19:32

1 Answers1

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

jpiazzal
  • 81
  • 6