我正在尝试使用 node.js 通过命令行打开文件。我正在使用 child_process.spawn,这是代码
var
process = require('child_process'),
cmd = process.spawn('cmd', ['start','tmp.txt'], {cwd: 'C:\\Users\\testuser\\Node_dev'});
我希望打开位于 Node_dev 文件夹中的文件 tmp.txt
但我收到错误 -
dir error { [Error: spawn ENOENT] code: 'ENONENT', errno: 'ENOENT', syscall: 'spawn'
我错过了什么?
此外,child_process.spawn
与 child_process.exec
之间有什么区别?
最佳答案
我没有对你的 ENOENT
错误的解释 [更新:事实证明这是一条红鲱鱼],但你的命令有一个问题是你启动cmd.exe
没有 /c
,这意味着生成的 shell 将 (a) 保持打开状态并且 (b) 实际上忽略指定的命令。
关于 child_process
模块的方法有何不同:
.execFile
和 .exec
接受一个回调,报告一个单个缓冲结果,而 .spawn
通过事件提供分块输出。
只有 .exec
将命令传递给平台的默认 shell,这更方便,但效率较低。
在您的情况下,您不关心生成的命令返回的输出,并且由于无论如何您都需要涉及 shell,.exec
是最佳选择。
在 Windows 上,使用 start
有其自身的缺陷:
- 它不是可执行文件,而是内置的 shell(用 Unix 术语来说)- 因此,它必须通过
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'});
关于node.js - Node js : Executing command line (opening a file),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27518718/