我正在尝试 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/