UNPKG

1.61 kBJavaScriptView Raw
1var exec = require('child_process').exec
2 , path = require('path')
3 ;
4
5
6/**
7 * open a file or uri using the default application for the file type.
8 *
9 * @return {ChildProcess} - the child process object.
10 * @param {string} target - the file/uri to open.
11 * @param {string} appName - (optional) the application to be used to open the
12 * file (for example, "chrome", "firefox")
13 * @param {function(Error)} callback - called with null on success, or
14 * an error object that contains a property 'code' with the exit
15 * code of the process.
16 */
17
18module.exports = open;
19
20function open(target, appName, callback) {
21 var opener;
22
23 if (typeof(appName) === 'function') {
24 callback = appName;
25 appName = null;
26 }
27
28 switch (process.platform) {
29 case 'darwin':
30 if (appName) {
31 opener = 'open -a "' + escape(appName) + '"';
32 } else {
33 opener = 'open';
34 }
35 break;
36 case 'win32':
37 // if the first parameter to start is quoted, it uses that as the title
38 // so we pass a blank title so we can quote the file we are opening
39 if (appName) {
40 opener = 'start "" "' + escape(appName) + '"';
41 } else {
42 opener = 'start ""';
43 }
44 break;
45 default:
46 if (appName) {
47 opener = escape(appName);
48 } else {
49 // use Portlands xdg-open everywhere else
50 opener = path.join(__dirname, './xdg-open');
51 }
52 break;
53 }
54
55 if (process.env.SUDO_USER) {
56 opener = 'sudo -u ' + process.env.SUDO_USER + ' ' + opener;
57 }
58 return exec(opener + ' "' + escape(target) + '"', callback);
59}
60
61function escape(s) {
62 return s.replace(/"/g, '\\\"');
63}