node.js - 为什么 execSync 在我的代码中不起作用?

标签 node.js exec child-process

我正在尝试 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);
^
TypeError: undefined is not a function
    at Object. (/home/User_Name/fil.js:24:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

为什么会这样?我应该更改什么才能使其正常工作?

最佳答案

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

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

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

sudo apt-get install -y nodejs

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

nodejs -v

关于node.js - 为什么 execSync 在我的代码中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39370559/

相关文章:

java - 安卓;使用执行("bugreport")

c - 了解执行和设置环境变量的要求

c - 如果 execlp 不包含 NULL 会怎样?

javascript - child_process.spawn 中奇怪的输出 "<Buffer"

mysql - 在 node.js 中使用 CURRENT_TIMESTAMP 更新 MySQL 表

node.js - 如何使用 expressJS 向客户端发送数据

node.js - 你如何捕获 SailsJS 中的所有错误

javascript - 关于快速 session 和 cookie,我缺少什么?

javascript - 使用字符串命令来子进程

node.js 通过管道从( fork 的)child_process 中输出流