javascript - How to get the output of a system command as a returned value from a function? -
the code shown below intended output present working directory console. instead outputs, "undefined". purposes of learning experience, important obtain desired result returned value of system function. ideas on how can make work?
#!/usr/bin/node var child_process = require('child_process'); function system(cmd) { child_process.exec(cmd, function (error, stdout, stderr) { return stdout; })}; console.log(system('pwd'));
exec executed asynchronously. pass callback function , you're set.
#!/usr/bin/node var child_process = require('child_process'); function system(cmd, callback) { child_process.exec(cmd, function (error, stdout, stderr) { //you should handle error or pass callback callback(stdout); }); } system('pwd', function(output){ console.log(output); });
and here's how synchronously, believe looking for.
function systemsync(cmd) { return child_process.execsync(cmd).tostring(); } console.log(systemsync("pwd"));
Comments
Post a Comment