summaryrefslogtreecommitdiff
path: root/lib/internal/process/esm_loader.js
blob: e7d70ebbca1ca4b722a0c0ec585a2da20133debd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
'use strict';

const { createModuleLoader } = require('internal/modules/esm/loader');
const { getOptionValue } = require('internal/options');
const {
  hasUncaughtExceptionCaptureCallback,
} = require('internal/process/execution');
const { pathToFileURL } = require('internal/url');
const { kEmptyObject } = require('internal/util');

let esmLoader;

module.exports = {
  get esmLoader() {
    return esmLoader ??= createModuleLoader(true);
  },
  async loadESM(callback) {
    esmLoader ??= createModuleLoader(true);
    try {
      const userImports = getOptionValue('--import');
      if (userImports.length > 0) {
        let cwd;
        try {
          // `process.cwd()` can fail if the parent directory is deleted while the process runs.
          cwd = process.cwd() + '/';
        } catch {
          cwd = '/';
        }
        const parentURL = pathToFileURL(cwd).href;
        await esmLoader.import(
          userImports,
          parentURL,
          kEmptyObject,
        );
      }
      await callback(esmLoader);
    } catch (err) {
      if (hasUncaughtExceptionCaptureCallback()) {
        process._fatalException(err);
        return;
      }
      internalBinding('errors').triggerUncaughtException(
        err,
        true, /* fromPromise */
      );
    }
  },
};