Woodland_Furniture
96 строк · 1.8 Кб
1'use strict';2const path = require('path');3const childProcess = require('child_process');4const isWsl = require('is-wsl');5
6module.exports = (target, opts) => {7if (typeof target !== 'string') {8return Promise.reject(new Error('Expected a `target`'));9}10
11opts = Object.assign({wait: true}, opts);12
13let cmd;14let appArgs = [];15let args = [];16const cpOpts = {};17
18if (Array.isArray(opts.app)) {19appArgs = opts.app.slice(1);20opts.app = opts.app[0];21}22
23if (process.platform === 'darwin') {24cmd = 'open';25
26if (opts.wait) {27args.push('-W');28}29
30if (opts.app) {31args.push('-a', opts.app);32}33} else if (process.platform === 'win32' || isWsl) {34cmd = 'cmd' + (isWsl ? '.exe' : '');35args.push('/c', 'start', '""', '/b');36target = target.replace(/&/g, '^&');37
38if (opts.wait) {39args.push('/wait');40}41
42if (opts.app) {43args.push(opts.app);44}45
46if (appArgs.length > 0) {47args = args.concat(appArgs);48}49} else {50if (opts.app) {51cmd = opts.app;52} else {53cmd = process.platform === 'android' ? 'xdg-open' : path.join(__dirname, 'xdg-open');54}55
56if (appArgs.length > 0) {57args = args.concat(appArgs);58}59
60if (!opts.wait) {61// `xdg-open` will block the process unless62// stdio is ignored and it's detached from the parent63// even if it's unref'd64cpOpts.stdio = 'ignore';65cpOpts.detached = true;66}67}68
69args.push(target);70
71if (process.platform === 'darwin' && appArgs.length > 0) {72args.push('--args');73args = args.concat(appArgs);74}75
76const cp = childProcess.spawn(cmd, args, cpOpts);77
78if (opts.wait) {79return new Promise((resolve, reject) => {80cp.once('error', reject);81
82cp.once('close', code => {83if (code > 0) {84reject(new Error('Exited with code ' + code));85return;86}87
88resolve(cp);89});90});91}92
93cp.unref();94
95return Promise.resolve(cp);96};97