方法一:
child_process
child_process 是 Node.js 的内置模块,该模块提供了衍生子进程的能力。
http://nodejs.cn/api/child_process.html
const exec = require('child_process').exec
exec('ipconfig', (error, stdout, stderr) => {
console.log(error, stdout, stderr)
})
方法二:
使用node-cmd包
https://www.npmjs.com/package/node-cmd
跟上面的方法其实一样的,看包的源码,使用的同样是child_process,举个例子
var nodeCmd = require('node-cmd')
function runCmdTest () {
nodeCmd.get(
'ipconfig',
(err, data, stderr)=> {
console.log('err', err, 'data', data, 'stderr', stderr)
}
)
// nodeCmd.run('命令行')也是同样效果
}
写在需要的文件中即可