为什么 execSync 在我的代码中不起作用?

问题描述 投票:0回答:2

我正在尝试nodejs中的各种子进程方法。因此,为了执行 Linux 命令,我尝试了这段代码,它打印了当前工作目录:

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

function commandOutput(error, stdout, stderr) {
    if (stderr !== null) {
        console.error(stderr);
    }
    if (error !== null) {
        console.error('execution error: ' + error);
    }
    if (stdout)console.log(stdout); 
    console.log("done");
}

var commandToExecute = "pwd";
execSync(commandToExecute, commandOutput);

console.log("executed");

虽然如果我用 exec 替换 execSync 可以正常工作,但上面的代码(即使用 execSync )会出现以下错误:

execSync(commandToExecute, commandOutput);
^
类型错误:未定义不是函数
    在对象。 (/home/用户名/fil.js:24:1)
    在 Module._compile (module.js:456:26)
    在 Object.Module._extensions..js (module.js:474:10)
    在 Module.load (module.js:356:32)
    在 Function.Module._load (module.js:312:12)
    在 Function.Module.runMain (module.js:497:10)
    启动时(node.js:119:16)
    在节点.js:902:3

为什么会发生这种情况?我应该改变什么才能让它发挥作用?

node.js exec child-process
2个回答
0
投票

尝试将您的节点更新到最新的稳定版本 6.10)

您可以通过运行来做到这一点:

curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -

sudo apt-get install -y nodejs

然后您可以通过运行来检查您的版本

nodejs -v

0
投票

您正在将回调传递给同步函数。
尝试使用

exec
而不是
execSync
。 如需进一步参考:https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

© www.soinside.com 2019 - 2024. All rights reserved.