问题描述
我正在编写一个执行“资源管理器中的显示文件”功能的Node脚本。我的代码可以归结为:
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',"/select"]
奇怪的是,当我使用/ select参数选择文件时,它仅在路径不包含任何空格时才起作用。如果路径中有空格,则默认为“文档”文件夹。
有什么办法解决吗?也许是一种使用反斜杠对空间进行编码的方法?还是explorer
命令的一些其他特殊参数?
解决方法
您缺少the documentation中针对windowsVerbatimArguments: true
和exec
的Windows特定的spawn
选项,但很容易错过。重要的是,默认情况下将其设置为 false ,这与您想要的相反。
以下工作正常:
const path = require("path");
const {exec,spawn} = require("child_process");
spawn(`explorer`,[
`/select,"${path.join(`C:`,`Program Files (x86)`,`Common Files`)}"`
],{ windowsVerbatimArguments: true });