【发布时间】:2015-07-06 07:06:18
【问题描述】:
我想给用户任何他想编辑文件的选项,我如何使用特定文件类型的默认程序打开文件?我需要它与 Windows 和 Linux 一起工作,但 Mac 选项也很棒。
【问题讨论】:
-
你能解释更多吗?你的问题不是很清楚
-
我有个文件路径,想用默认程序打开
标签: javascript linux windows node.js node-webkit
我想给用户任何他想编辑文件的选项,我如何使用特定文件类型的默认程序打开文件?我需要它与 Windows 和 Linux 一起工作,但 Mac 选项也很棒。
【问题讨论】:
标签: javascript linux windows node.js node-webkit
正如PSkocik所说,首先检测平台并获取命令行:
function getCommandLine() {
switch (process.platform) {
case 'darwin' : return 'open';
case 'win32' : return 'start';
case 'win64' : return 'start';
default : return 'xdg-open';
}
}
其次,执行命令行后跟路径
var exec = require('child_process').exec;
exec(getCommandLine() + ' ' + filePath);
【讨论】:
var sys = require('sys'); 它没有被使用。我不知道为什么我将它包含在解决方案中。我现在会更新答案。
case: 'win64',因为 process.platform 是“win32”,即使在 64 位版本的 Windows 上 (source)
您可以使用open 模块:
npm install --save open
然后在你的 Node.js 文件中调用它:
const open = require('open');
open('my-file.txt');
此模块已包含检测操作系统的逻辑,它运行您的系统与此文件类型关联的默认程序。
【讨论】:
对于磁盘上的文件:
var nwGui = require('nw.gui');
nwGui.Shell.openItem("/path/to/my/file");
对于远程文件(例如网页):
var nwGui = require('nw.gui');
nwGui.Shell.openExternal("http://google.com/");
【讨论】:
检测平台并使用:
【讨论】:
我不确定 start 是否可以在早期的 Windows 版本上正常工作,但是在 Windows 10 上它不能如答案中所示工作。它的第一个参数是窗口的标题。
此外,windows 和 linux 之间的行为是不同的。 Windows "start" 将执行并退出,在 linux 下,xdg-open 将等待。
这是最终在两个平台上以类似方式为我工作的功能:
function getCommandLine() {
switch(process.platform) {
case 'darwin' :
return 'open';
default:
return 'xdg-open';
}
}
function openFileWithDefaultApp(file) {
/^win/.test(process.platform) ?
require("child_process").exec('start "" "' + file + '"') :
require("child_process").spawn(getCommandLine(), [file],
{detached: true, stdio: 'ignore'}).unref();
}
【讨论】:
如果您打算使用默认编辑器编写某种提示脚本,或者只是链式打开文件,您将不得不等到程序结束或失败。
const {exec} = require('child_process');
let openFile=function(filePath,mute){
let command=(function() {
switch (process.platform) {
case 'darwin' : return 'open '+filePath+' && lsof -p $! +r 1 &>/dev/null';
case 'win32' :
case 'win64' : return 'start /wait '+filePath;
default : return 'xdg-open '+filePath+' && tail --pid=$! -f /dev/null';
}
})();
if(!mute)console.log(command);
let child=exec(command);
if(!mute)child.stdout.pipe(process.stdout);
return new function(){
this.on=function(type,callback){
if(type==='data')child.stdout.on('data',callback);
else if(type==='error')child.stderr.on('data',callback);
else child.on('exit',callback);
return this;
};
this.toPromise=function(){
return new Promise((then,fail)=>{
let out=[];
this.on('data',d=>out.push(d))
.on('error',err=>fail(err))
.on('exit',()=>then(out));
});
};
}();
};
使用:
openFile('path/to/some_text.txt')
.on('data',data=>{
console.log('output :'+data);
})
.on('error',err=>{
console.log('error :'+err);
})
.on('exit',()=>{
console.log('done');
});
或:
openFile('path/to/some_text.txt').toPromise()
.then(output=>{
console.log('done output :'+output.join('\n'));
}).catch(err=>{
console.log('error :'+err);
});
PS:如果它等待除 winXX 以外的其他系统,请告诉我(灵感来自 Rauno Palosaari post,但尚未测试)。
【讨论】: