[英]Node js: Executing command line (opening a file)
我正在尝试使用 node.js 通过命令行打开文件。 我正在使用 child_process.spawn,这是代码
var
process = require('child_process'),
cmd = process.spawn('cmd', ['start','tmp.txt'], {cwd: 'C:\\Users\\testuser\\Node_dev'});
我希望tmp.txt
位于 Node_dev 文件夹中的文件tmp.txt
,但出现错误 -
dir error { [Error: spawn ENOENT] code: 'ENONENT', errno: 'ENOENT', syscall: 'spawn'
我错过了什么?
另外, child_process.spawn
与child_process.exec
之间有什么区别?
我没有解释您的ENOENT
错误 [更新:原来这是一个红鲱鱼],但是您的命令的一个问题是您在没有/c
情况下启动了cmd.exe
,这意味着生成的 shell 将 (a) 保持不变open 和 (b) 实际上忽略指定的命令。
至于child_process
模块的方法child_process
不同:
.execFile
和.exec
接受报告单个缓冲结果的回调,而.spawn
通过 events提供分块输出。
只有.exec
将命令传递给平台的默认 shell ,这使其更方便,但效率较低。
在您的情况下,您不关心从生成的命令返回的输出,并且由于您无论如何都需要涉及 shell,因此.exec
是最佳选择。
在 Windows 上,使用start
有其自身的缺陷:
cmd.exe
调用。 以下是应该在 Windows 上运行的调用 - 请注意,它们都异步启动子进程并忽略它的任何输出- 它们所做的只是告诉cmd.exe
打开指定的文件,就像用户在资源管理器中打开它一样:
.exec
:var cpm = require('child_process');
// With .exec, specify the entire shell command as the 1st argument - it is implicitly
// passed to cmd.exe.
// '""' as the 1st argument to `start` is an empty window title that ensures that any
// filename argument with embedded spaces isn't mistaken for a window title.
cpm.exec('start "" "tmp.txt"', {cwd: 'C:\\Users\\testuser\\Node_dev'});
.execFile
或.spawn
:// With .spawn or .execFile, specify `cmd` as the 1st argument, and the shell command
// tokens as an array passed as the 2nd argument.
// Note the /c, which ensures that cmd exits after having executed the specified
// command.
// '""' as the 1st argument to `start` is an empty window title that ensures that any
// filename argument with embedded spaces isn't mistaken for a window title.
cpm.spawn('cmd', [ '/c', 'start', '""', 'tmp.txt' ], {cwd: 'C:\\Users\\testuser\\Node_dev'});
npm 上有一个名为open
的跨平台模块,它使用操作系统的默认处理程序打开文件,您可以将其用作指南或按原样使用。
不过,要在 Windows 上使用 spawn 手动执行此操作,您需要执行以下操作:
var args = ['/s', '/c', 'start', '', 'tmp.txt'],
opts = { cwd: 'C:\\Users\\testuser\\Node_dev' },
child = child_process.spawn('cmd.exe', args, opts);
child_process.exec()
基本上是一个更高级别的包装child_process.spawn()
它缓冲输出,然后经过缓冲的输出和错误输出到回调。
我使用的是相同的,这是我的命令,可以使用参数运行和执行:
var exec = require('child_process').spawn;
let scanProcess = exec('cmd', [ '/c', 'start', '""', 'feature.exe --version' ], {cwd: 'command_folder'});
我在运行 Windows 操作系统的容器中的 Azure DevOps 上运行它。 上面的命令没有回来,它挂了。 任何指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.