NodeJS:child_process.exec没有执行函数

str*_*ght 5 javascript child-process node.js gruntjs

我正在尝试做一些我认为非常简单的事情 - 使用child_process.exec执行'echo'行.我的代码看起来像这样:

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

exec('echo "HELLO"', function (error, stdout, stderr) {
    console.log(error);
    console.log(stdout);
    console.log(stderr);
});
Run Code Online (Sandbox Code Playgroud)

截至目前,回声永远不会被调用,回调也不会被调用.这里有什么我想念的吗?

另外,我正在使用我正在创建的grunt任务中的thins,所以我不确定是否有任何可以将其设置的东西(尽管这个插件似乎在这里做得很好 - https:// github. com/sindresorhus/grunt-shell/blob/master/tasks/shell.js)

小智 3

你的代码很好。

您遇到的问题可能与回调有关,如果您使用execSyncchild_process 它可能会工作。

如果您想exec在 grunt 任务中保留带有回调的函数,请使用this.async();

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

看看这里: https: //gruntjs.com/api/inside-tasks