(Node.js 子进程)带有 /select 选项的生成资源管理器不适用于路径中的空格

(Node.js child process) Spawning explorer, with /select option, does not work with spaces in path

我正在编写一个执行“在资源管理器中显示文件”功能的节点脚本。我的代码归结为:

const {spawn} = require('child_process');

// This works (it opens C:/path/to/file and highlights the file named "WithoutSpaces"
spawn('explorer', ["C:\path\to\file\WithoutSpaces,", "/select"]);

// However, this does not work. It defaults to opening a file explorer window with my Documents folder.
spawn('explorer', ["C:\this path\has spaces,", "/select"]
spawn('explorer', ["C:\this path\has spaces\file.txt,", "/select"]

// Strangely, spaces DO work if I'm not doing the /select option:
spawn('explorer', ["C:\this path\has spaces,", "/select"]

奇怪的是,当我对 select 文件使用 /select 参数时,它仅在路径不包含任何 space 时有效。如果路径确实有 space,则默认为 Documents 文件夹。

有什么办法解决这个问题吗?也许是一种用反斜杠编码 space 的方法?或者 explorer 命令的一些其他特殊参数?

您缺少 windows-specific windowsVerbatimArguments: true 选项,execspawn 都列在 the documentation 中,但很容易错过。至关重要的是,这默认设置为 false,这与您想要的相反。

以下工作正常:

const path = require("path");
const {exec, spawn} = require("child_process");

spawn(`explorer`, [
  `/select,"${path.join(`C:`, `Program Files (x86)`, `Common Files`)}"`
], { windowsVerbatimArguments: true });