Node.js 如何使用节点JS执行Windows Shell命令(Cmd.exe)
我想Node.js 如何使用节点JS执行Windows Shell命令(Cmd.exe),node.js,cmd,windows-shell,Node.js,Cmd,Windows Shell,我想 C:\>ACommandThatGetsData > save.txt 但是我不想在控制台中解析和保存数据,而是想使用Node.JS执行上面的命令 如何使用Node.JS执行shell命令?使用: 更新 我应该把这些文件读得更好 有一个允许执行子进程的。您需要子进程.exec,子进程.execFile或子进程.spawn。所有这些在使用上都是相似的,但每个都有自己的优势。根据您的需要,您可以选择使用哪一款。您也可以尝试以下软件包: 我知道这个问题由来已久,但它帮助我通过承诺
C:\>ACommandThatGetsData > save.txt
但是我不想在控制台中解析和保存数据,而是想使用Node.JS执行上面的命令
如何使用Node.JS执行shell命令?使用:
更新
我应该把这些文件读得更好
有一个允许执行子进程的。您需要子进程.exec
,子进程.execFile
或子进程.spawn
。所有这些在使用上都是相似的,但每个都有自己的优势。根据您的需要,您可以选择使用哪一款。您也可以尝试以下软件包:
我知道这个问题由来已久,但它帮助我通过承诺找到了解决方案。 另见:
可能的重复可能的重复解决了我撞到的砖墙!谢谢:)
process.execPath('/path/to/executable');
const nodeCmd = require('node-cmd');
nodeCmd.get('dir', (err, data, stderr) => console.log(data));
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();