NodeJS执行系统命令

在NodeJS中执行系统命令可以使用child_process的exec函数

const exec = require('child_process').exec;
const child = exec('ll /webs | wc -l', (error, stdout, stderr) => {
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
  if (error !== null) {
    console.log(`exec error: ${error}`);
  }
});

只不过跟其它语言不同的是NodeJS里绝大部分操作都是异步,也就是非阻塞操作,需要在回调函数里处理结果,包括错误。当然,也会提供同步的函数

const execSync = require('child_process').execSync;
const output = execSync('ll /webs | wc -l');
console.log(output);
分享

TITLE: NodeJS执行系统命令

LINK: https://www.qttc.net/445-nodejs-exec.html

NOTE: 原创内容,转载请注明出自琼台博客