main.js (2397B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var spawn = require( 'child_process' ).spawn; 24 var IS_WINDOWS = require( '@stdlib/assert/is-windows' ); 25 var IS_DARWIN = require( '@stdlib/assert/is-darwin' ); 26 var isURI = require( '@stdlib/assert/is-uri' ); 27 28 29 // VARIABLES // 30 31 var ARGS; 32 var CMD; 33 34 // Mac: 35 if ( IS_DARWIN ) { 36 CMD = 'open'; 37 ARGS = []; 38 } 39 // On Windows, ideally, we would use the `start` command; however, the rules regarding argument spacing and escaping are complex. Instead, we can use `cmd /c` which has built-in logic to address these rules. 40 else if ( IS_WINDOWS ) { 41 CMD = 'cmd'; 42 43 // `cmd /c` interprets double-quoted first parameters as window titles. To work around this, we explicitly provide an empty string for the window title. 44 ARGS = [ '/c', 'start', '""' ]; 45 } 46 // All other `*nix` flavors: 47 else { 48 CMD = 'xdg-open'; 49 ARGS = []; 50 } 51 52 53 // MAIN // 54 55 /** 56 * Opens a URL. 57 * 58 * @param {string} url - URL to open 59 * @throws {TypeError} must provide a valid URI 60 * @returns {Process} spawned process (unreferenced) 61 * 62 * @example 63 * var proc = openURL( 'https://google.com' ); 64 */ 65 function openURL( url ) { 66 var args; 67 var proc; 68 var i; 69 if ( !isURI( url ) ) { 70 throw new TypeError( 'invalid input value. Must provide a valid URI. Value: `' + url + '`.' ); 71 } 72 args = new Array( ARGS.length ); 73 for ( i = 0; i < ARGS.length; i++ ) { 74 args[ i ] = ARGS[ i ]; 75 } 76 if ( IS_WINDOWS ) { 77 // `&` characters must be escaped when passed to `start`: 78 url = url.replace( /&/g, '^&' ); 79 } 80 args.push( url ); 81 82 // Spawn a child process to open the URL: 83 proc = spawn( CMD, args, {} ); 84 85 // To prevent the parent process waiting on the child process, we unreference the process to remove it from the parent's reference count: 86 proc.unref(); 87 88 return proc; 89 } 90 91 92 // EXPORTS // 93 94 module.exports = openURL;