簡體   English   中英

如何使用 Node JS 執行 Windows Shell 命令 (Cmd.exe)

[英]How To Execute Windows Shell Commands (Cmd.exe) with Node JS

我想要

C:\>ACommandThatGetsData > save.txt

但是我不想在控制台中解析和保存數據,而是想用Node.JS執行上述命令

如何使用Node.JS執行 shell 命令?

使用 process.execPath()

 
 
 
  
  process.execPath('/path/to/executable');
 
 

更新

我應該更好地閱讀文檔。

有一個允許執行子進程的子進程模塊 您將需要child_process.execchild_process.execFilechild_process.spawn 所有這些在使用上都是相似的,但每個都有自己的優點。 使用它們中的哪一個取決於您的需要。

你也可以試試node-cmd包:

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM