1.开源库的简介
跨平台的,在命令行打开URL、文件、可执行文件等内容。
在MacOS使用command open ,Windows使用命令start ,其他系统使用 xdg-open
官网npmjs:https://www.npmjs.com/package/open
1.1使用方法:
// Opens the URL in the default browser.await open('https://sindresorhus.com');// Opens the URL in a specified browser.await open('https://sindresorhus.com', {app: {name: 'firefox'}});// Specify app arguments.await open('https://sindresorhus.com', {app: {name: 'google chrome', arguments: ['--incognito']}});
2.源码分析
源码中最主要的是一个方法baseOpen,根据系统的不同,采用不同的方式。
方法的结构如下:
对系统分类三类,根据不同的类型来初始化command,cliArguments和childProcessOptions。在确定了这三个东西之后,开启一个node子进程childProcess.spawn。
const baseOpen = async options => {options = {wait: false,background: false,newInstance: false,allowNonzeroExitCode: false,...options};let {name: app, arguments: appArguments = []} = options.app || {};appArguments = [...appArguments]; // [] 空数组let command;const cliArguments = [];const childProcessOptions = {};if (platform === 'darwin') { // darwin 操作系统command = 'open';...} else if (platform === 'win32' || (isWsl && !isDocker())) {const mountPoint = await getWslDrivesMountPoint();command = isWsl ?`${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` :`${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`;// Using Base64-encoded command, accepted by PowerShell, to allow special characters.options.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');...} else {...}const subprocess = childProcess.spawn(command,cliArguments,childProcessOptions);if (options.wait) {return new Promise((resolve, reject) => {subprocess.once('error', reject);subprocess.once('close', exitCode => {if (options.allowNonzeroExitCode && exitCode > 0) {reject(new Error(`Exited with code ${exitCode}`));return;}resolve(subprocess);});});}// 默认情况下,父进程将等待分离的子进程退出。 为了防止父进程等待给定的 subprocess 退出,则使用 subprocess.unref() 方法。 这样做会使父进程的事件循环不将子进程包括在其引用计数中,从而允许父进程独立于子进程退出,除非在子进程和父进程之间建立了 IPC 通道。subprocess.unref();return subprocess;};
child_process.spawn() 方法异步衍生子进程,不会阻塞 Node.js 事件循环。
child_process.spawnSync() 函数以同步方式提供等效的功能,其会阻塞事件循环,直到衍生的进程退出或终止。
subprocess.unref()// 默认情况下,父进程将等待分离的子进程退出。 为了防止父进程等待给定的 subprocess 退出,则使用 subprocess.unref() 方法。 这样做会使父进程的事件循环不将子进程包括在其引用计数中,从而允许父进程独立于子进程退出,除非在子进程和父进程之间建立了 IPC 通道。
所以整个源码就在做一件事情。(如下面代码),根据不同的系统,来确定不同的三个参数command, args, options而已。
const childProcess = require('child_process');const command = "open";const args = ['https://lxchuan12.gitee.io'];const options = {};let ls = childProcess.spawn(command, args, options)ls.on('close', (code) => {console.log(`child process close all stdio with code ${code}`);});ls.on('exit', (code) => {console.log(`child process exited with code ${code}`);});
