Reputation: 1558
I'm trying out various child process methods in nodejs. So to execute a linux command, I tried this code, where it prints the current working directory:
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");
While this works fine if I replace execSync with exec, the above code, i.e, with execSync gives the following error:
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
Why is this happening? What should I change for this to work?
Upvotes: 3
Views: 11480
Reputation: 424
You are passing a callback to a sync function.
Try using exec
instead of execSync
.
For further reference: https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
Upvotes: 0
Reputation: 19
Try updating your Node to the latest stable version 6.10)
You can do that by running:
curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
sudo apt-get install -y nodejs
You can then check your version by running
nodejs -v
Upvotes: 0