/ src / main-process / atom-protocol-handler.js
atom-protocol-handler.js
 1  const { protocol } = require('electron');
 2  const fs = require('fs-plus');
 3  const path = require('path');
 4  
 5  // Handles requests with 'atom' protocol.
 6  //
 7  // It's created by {AtomApplication} upon instantiation and is used to create a
 8  // custom resource loader for 'atom://' URLs.
 9  //
10  // The following directories are searched in order:
11  //   * ~/.atom/assets
12  //   * ~/.atom/dev/packages (unless in safe mode)
13  //   * ~/.atom/packages
14  //   * RESOURCE_PATH/node_modules
15  //
16  module.exports = class AtomProtocolHandler {
17    constructor(resourcePath, safeMode) {
18      this.loadPaths = [];
19  
20      if (!safeMode) {
21        this.loadPaths.push(path.join(process.env.ATOM_HOME, 'dev', 'packages'));
22        this.loadPaths.push(path.join(resourcePath, 'packages'));
23      }
24  
25      this.loadPaths.push(path.join(process.env.ATOM_HOME, 'packages'));
26      this.loadPaths.push(path.join(resourcePath, 'node_modules'));
27  
28      this.registerAtomProtocol();
29    }
30  
31    // Creates the 'atom' custom protocol handler.
32    registerAtomProtocol() {
33      protocol.registerFileProtocol('atom', (request, callback) => {
34        const relativePath = path.normalize(request.url.substr(7));
35  
36        let filePath;
37        if (relativePath.indexOf('assets/') === 0) {
38          const assetsPath = path.join(process.env.ATOM_HOME, relativePath);
39          const stat = fs.statSyncNoException(assetsPath);
40          if (stat && stat.isFile()) filePath = assetsPath;
41        }
42  
43        if (!filePath) {
44          for (let loadPath of this.loadPaths) {
45            filePath = path.join(loadPath, relativePath);
46            const stat = fs.statSyncNoException(filePath);
47            if (stat && stat.isFile()) break;
48          }
49        }
50  
51        callback(filePath);
52      });
53    }
54  };