open a file with default program in node-webkit

两盒软妹~` 提交于 2019-12-03 14:04:42

问题


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.


回答1:


as PSkocik said, first detect the platform and get the command line :

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 sys = require('sys');
var exec = require('child_process').exec;

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



回答2:


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/");



回答3:


Detect the platform and use:

  • 'start' on Windows
  • 'open' on Macs
  • 'xdg-open' on Linux



回答4:


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. It's first argument is the title of the window.

Furthermore the behavior between windows and linux is different. Windows "start" will exec and exit, under linux, xdg-open will wait.

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


来源:https://stackoverflow.com/questions/29902347/open-a-file-with-default-program-in-node-webkit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!