简体   繁体   English

在 node-webkit 中用默认程序打开一个文件

[英]open a file with default program in node-webkit

I want to give the user any option he want to edit a file, how can I open a file with the default program of the specific file type?我想为用户提供他想要编辑文件的任何选项,如何使用特定文件类型的默认程序打开文件? I need it to work with Windows and Linux but Mac option would be great too.我需要它与 Windows 和 Linux 一起使用,但 Mac 选项也很棒。

as PSkocik said, first detect the platform and get the command line :正如PSkocik所说,首先检测平台并获取命令行:

function getCommandLine() {
   switch (process.platform) { 
      case 'darwin' : return 'open';
      case 'win32' : return 'start';
      case 'win64' : return 'start';
      default : return 'xdg-open';
   }
}

second , execute the command line followed by the path其次,执行命令行后跟路径

var exec = require('child_process').exec;

exec(getCommandLine() + ' ' + filePath);

You can use the open module:您可以使用开放模块:

npm install --save open

and then call it in your Node.js file:然后在你的 Node.js 文件中调用它:

const open = require('open');
open('my-file.txt');

This module already contains the logic to detect the operating system and it runs the default program that is associated to this file type by your system.该模块已经包含检测操作系统的逻辑,它运行与您的系统相关联的默认程序。

For file on a disk:对于磁盘上的文件:

var nwGui = require('nw.gui');
nwGui.Shell.openItem("/path/to/my/file");

For remote files (eg web page):对于远程文件(例如网页):

var nwGui = require('nw.gui');
nwGui.Shell.openExternal("http://google.com/");

Detect the platform and use:检测平台并使用:

  • 'start' on Windows在 Windows 上“开始”
  • 'open' on Macs在 Mac 上“打开”
  • 'xdg-open' on Linux Linux 上的“xdg-open”

I am not sure if start used to work as is on earlier windows versions, however on windows 10 it doesn't work as indicated in the answer.我不确定 start 是否可以在早期的 Windows 版本上正常工作,但是在 Windows 10 上它不能像答案中所示那样工作。 It's first argument is the title of the window.它的第一个参数是窗口的标题。

Furthermore the behavior between windows and linux is different.此外,windows 和 linux 之间的行为是不同的。 Windows "start" will exec and exit, under linux, xdg-open will wait. Windows“start”会执行并退出,在linux下,xdg-open会等待。

This was the function that eventually worked for me on both platforms in a similar manner:这是最终在两个平台上以类似方式为我工作的功能:

  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(); 
  }

If you aim to script some kind of prompt with a default editor or simply chain files opening, you will have to wait until the program ends or fail.如果您打算使用默认编辑器编写某种提示或简单地打开链接文件,则必须等到程序结束或失败。

Inspired from PSkocik and Khalid answers.灵感来自PSkocikKhalid 的答案。

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));
            });
        };
    }();
};

use :用 :

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');
});

or :或者 :

openFile('path/to/some_text.txt').toPromise()
.then(output=>{
    console.log('done output :'+output.join('\n'));
}).catch(err=>{
    console.log('error :'+err);
});

PS : Let me know if it waits for other sytems than winXX ( Inspired from Rauno Palosaari post but not tested yet ). PS:让我知道它是否等待 winXX 以外的其他系统(灵感来自Rauno Palosaari 帖子但尚未测试)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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