繁体   English   中英

Node js:执行命令行(打开文件)

[英]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.spawnchild_process.exec之间有什么区别?

我没有解释您的ENOENT错误 [更新:原来这是一个红鲱鱼],但是您的命令的一个问题是您在没有/c情况下启动了cmd.exe ,这意味着生成的 shell 将 (a) 保持不变open 和 (b) 实际上忽略指定的命令。

至于child_process模块的方法child_process不同:

.execFile.exec接受报告单个缓冲结果回调,而.spawn通过 events提供分块输出
只有.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'});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM