在ms Windows平台上,如何使用node.js代码打开Windows文件资源管理器中的特定目录(例如:c:\documents
)?
我猜在c#中,可以这样写:
process.Start(@"c:\test")
在ms Windows平台上,如何使用node.js代码打开Windows文件资源管理器中的特定目录(例如:c:\documents
)?
我猜在c#中,可以这样写:
process.Start(@"c:\test")
请尝试以下操作,它会在运行Node.js的计算机上打开文件资源管理器窗口:
require('child_process').exec('start "" "c:\\test"');
如果你的路径不包含空格,你也可以通过使用 'start c:\\test'
来实现,但上述方法是最健壮的,因为它需要将 ""
作为第二个参数[1]。
注意:
文件资源管理器窗口将异步启动,并在启动时获得焦点。
这个相关问题 请求一个防止窗口“抢占”焦点的解决方案。
[1] 默认情况下,cmd.exe
的内部start
命令将以 "..."
包含的第一个参数解释为新控制台窗口的窗口标题(这里不适用)。通过明确提供(虚拟的)窗口标题-""
,第二个参数可被可靠地解释为目标可执行文件/文档路径。
使用这个包会很有益,因为它可以在不同的平台上打开文件资源管理器。 https://www.npmjs.com/package/open-file-explorer
或者只使用其中的一部分。
function openExplorerin(path, callback) {
var cmd = ``;
switch (require(`os`).platform().toLowerCase().replace(/[0-9]/g, ``).replace(`darwin`, `macos`)) {
case `win`:
path = path || '=';
cmd = `explorer`;
break;
case `linux`:
path = path || '/';
cmd = `xdg-open`;
break;
case `macos`:
path = path || '/';
cmd = `open`;
break;
}
let p = require(`child_process`).spawn(cmd, [path]);
p.on('error', (err) => {
p.kill();
return callback(err);
});
}
我在WSL和可能的Windows系统中找到了另一种方法。
请注意,您必须确保为Windows而不是Linux(WSL)格式化路径。
我想要在Windows上保存一些东西,为此你需要使用WSL上的/mnt
目录。
// format the path, so Windows isn't mad at us
// first we specify that we want the path to be compatible with windows style
// then we replace the /mnt/c/ with the format that windows explorer accepts
// the path would look like `c:\\Users\some\folder` after this line
const winPath = path.win32.resolve(dir).replace('\\mnt\\c\\', 'c:\\\\');
// then we use the same logic as the previous answer but change it up a bit
// do remember about the "" if you have spaces in your name
require('child_process').exec(`explorer.exe "${winPath}"`);
这应该为您打开文件浏览器。
let explorer;
switch (platform()) {
case "win32": explorer = "explorer"; break;
case "linux": explorer = "xdg-open"; break;
case "darwin": explorer = "open"; break;
}
spawn(explorer, [path], { detached: true }).unref();
platform()
来自于os
模块,而spawn
来自于child_process
模块。
explorer-opener
软件包:import { openExplorer } from 'explorer-opener';
openExplorer('C:\\Windows\\System32')
.then(() => {
// handle successful open
})
.catch((error) => {
// handle error
});