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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15919347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:10:13  来源:igfitidea点击:

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

node.jscmdwindows-shell

提问by FredTheWebGuy

I would like to

我想要

C:\>ACommandThatGetsData > save.txt

But instead of parsing and saving the data in the console, I would like to do the above command with Node.JS

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

How to execute a shell command with Node.JS?

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

采纳答案by Haroldo_OK

You could also try the node-cmdpackage:

你也可以试试node-cmd包:

const nodeCmd = require('node-cmd');
nodeCmd.get('dir', (err, data, stderr) => console.log(data));

回答by Shimon Rachlenko

Use process.execPath():

使用process.execPath()

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

Update

更新

I should have read the documentations better.

我应该更好地阅读文档。

There is a Child Process Modulewhich allows to execute a child process. You will need either child_process.exec, child_process.execFileor child_process.spawn. All of these are similar in use, but each has its own advantages. Which of them to use depends on your needs.

有一个允许执行子进程的子进程模块。您将需要child_process.exec,child_process.execFilechild_process.spawn。所有这些在使用上都是相似的,但每个都有自己的优点。使用它们中的哪一个取决于您的需要。