Execute and get the output of a shell command in node.js

前端 未结 5 570
无人及你
无人及你 2020-11-27 10:56

In a node.js, I\'d like to find a way to obtain the output of a Unix terminal command. Is there any way to do this?

function getCommandOutput(commandString){         


        
5条回答
  •  感情败类
    2020-11-27 11:26

    You're looking for child_process

    var exec = require('child_process').exec;
    var child;
    
    child = exec(command,
       function (error, stdout, stderr) {
          console.log('stdout: ' + stdout);
          console.log('stderr: ' + stderr);
          if (error !== null) {
              console.log('exec error: ' + error);
          }
       });
    

    As pointed out by Renato, there are some synchronous exec packages out there now too, see sync-exec that might be more what yo're looking for. Keep in mind though, node.js is designed to be a single threaded high performance network server, so if that's what you're looking to use it for, stay away from sync-exec kinda stuff unless you're only using it during startup or something.

提交回复
热议问题