1.开源库的简介

跨平台的,在命令行打开URL、文件、可执行文件等内容。
在MacOS使用command open ,Windows使用命令start ,其他系统使用 xdg-open

官网npmjs:https://www.npmjs.com/package/open

1.1使用方法:

  1. // Opens the URL in the default browser.
  2. await open('https://sindresorhus.com');
  3. // Opens the URL in a specified browser.
  4. await open('https://sindresorhus.com', {app: {name: 'firefox'}});
  5. // Specify app arguments.
  6. await open('https://sindresorhus.com', {app: {name: 'google chrome', arguments: ['--incognito']}});

2.源码分析

源码中最主要的是一个方法baseOpen,根据系统的不同,采用不同的方式。
方法的结构如下:
对系统分类三类,根据不同的类型来初始化command,cliArguments和childProcessOptions。在确定了这三个东西之后,开启一个node子进程childProcess.spawn。

  1. const baseOpen = async options => {
  2. options = {
  3. wait: false,
  4. background: false,
  5. newInstance: false,
  6. allowNonzeroExitCode: false,
  7. ...options
  8. };
  9. let {name: app, arguments: appArguments = []} = options.app || {};
  10. appArguments = [...appArguments]; // [] 空数组
  11. let command;
  12. const cliArguments = [];
  13. const childProcessOptions = {};
  14. if (platform === 'darwin') { // darwin 操作系统
  15. command = 'open';
  16. ...
  17. } else if (platform === 'win32' || (isWsl && !isDocker())) {
  18. const mountPoint = await getWslDrivesMountPoint();
  19. command = isWsl ?
  20. `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` :
  21. `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
  22. // Using Base64-encoded command, accepted by PowerShell, to allow special characters.
  23. options.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');
  24. ...
  25. } else {
  26. ...
  27. }
  28. const subprocess = childProcess.spawn(
  29. command,
  30. cliArguments,
  31. childProcessOptions
  32. );
  33. if (options.wait) {
  34. return new Promise((resolve, reject) => {
  35. subprocess.once('error', reject);
  36. subprocess.once('close', exitCode => {
  37. if (options.allowNonzeroExitCode && exitCode > 0) {
  38. reject(new Error(`Exited with code ${exitCode}`));
  39. return;
  40. }
  41. resolve(subprocess);
  42. });
  43. });
  44. }
  45. // 默认情况下,父进程将等待分离的子进程退出。 为了防止父进程等待给定的 subprocess 退出,则使用 subprocess.unref() 方法。 这样做会使父进程的事件循环不将子进程包括在其引用计数中,从而允许父进程独立于子进程退出,除非在子进程和父进程之间建立了 IPC 通道。
  46. subprocess.unref();
  47. return subprocess;
  48. };

child_process.spawn() 方法异步衍生子进程,不会阻塞 Node.js 事件循环。

child_process.spawnSync() 函数以同步方式提供等效的功能,其会阻塞事件循环,直到衍生的进程退出或终止。

subprocess.unref()// 默认情况下,父进程将等待分离的子进程退出。 为了防止父进程等待给定的 subprocess 退出,则使用 subprocess.unref() 方法。 这样做会使父进程的事件循环不将子进程包括在其引用计数中,从而允许父进程独立于子进程退出,除非在子进程和父进程之间建立了 IPC 通道。

所以整个源码就在做一件事情。(如下面代码),根据不同的系统,来确定不同的三个参数command, args, options而已。

  1. const childProcess = require('child_process');
  2. const command = "open";
  3. const args = ['https://lxchuan12.gitee.io'];
  4. const options = {};
  5. let ls = childProcess.spawn(command, args, options)
  6. ls.on('close', (code) => {
  7. console.log(`child process close all stdio with code ${code}`);
  8. });
  9. ls.on('exit', (code) => {
  10. console.log(`child process exited with code ${code}`);
  11. });