【发布时间】:2013-04-01 21:51:18
【问题描述】:
我愿意
C:\>ACommandThatGetsData > save.txt
但不是在控制台中解析和保存数据,我想用 Node.JS
执行上述命令如何使用 Node.JS 执行 shell 命令?
【问题讨论】:
标签: node.js cmd windows-shell
我愿意
C:\>ACommandThatGetsData > save.txt
但不是在控制台中解析和保存数据,我想用 Node.JS
执行上述命令如何使用 Node.JS 执行 shell 命令?
【问题讨论】:
标签: node.js cmd windows-shell
process.execPath('/path/to/executable');
我应该更好地阅读文档。
有一个Child Process Module 允许执行子进程。您将需要child_process.exec、child_process.execFile 或child_process.spawn。所有这些在使用上都是相似的,但每个都有自己的优点。使用哪一个取决于您的需求。
【讨论】:
你也可以试试node-cmd 包:
const nodeCmd = require('node-cmd');
nodeCmd.get('dir', (err, data, stderr) => console.log(data));
【讨论】:
我知道这个问题很老,但它帮助我使用 Promise 找到了我的解决方案。 另见:this question & answer
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function runCommand(command) {
const { stdout, stderr, error } = await exec(command);
if(stderr){console.error('stderr:', stderr);}
if(error){console.error('error:', error);}
return stdout;
}
async function myFunction () {
// your code here building the command you wish to execute ...
const command = 'dir';
const result = await runCommand(command);
console.log("_result", result);
// your code here processing the result ...
}
// just calling myFunction() here so it runs when the file is loaded
myFunction();
【讨论】: