From 8beaac38c1d0a6ee8e1268bb97cdd7c580f402e7 Mon Sep 17 00:00:00 2001 From: Myles Borins Date: Thu, 25 Apr 2019 00:29:22 -0400 Subject: [PATCH 1/3] module: add createRequire method This is an abstraction on top of creatRequireFromPath that can accept both paths, URL Strings, and URL Objects. PR-URL: https://github.com/nodejs/node/pull/27405 Reviewed-By: Benjamin Gruenbaum Reviewed-By: James M Snell Reviewed-By: Jan Krems Reviewed-By: Jeremiah Senkpiel Reviewed-By: Ruben Bridgewater Reviewed-By: Rich Trott --- doc/api/deprecations.md | 1 - doc/api/modules.md | 20 +++++++++ lib/internal/modules/cjs/loader.js | 48 ++++++++++++++++++--- test/fixtures/experimental | 1 + test/parallel/test-module-create-require.js | 24 ++++++++++- 5 files changed, 86 insertions(+), 8 deletions(-) create mode 100644 test/fixtures/experimental diff --git a/doc/api/deprecations.md b/doc/api/deprecations.md index 90c2ad5d4f2197..87e537ee4dd194 100644 --- a/doc/api/deprecations.md +++ b/doc/api/deprecations.md @@ -2107,7 +2107,6 @@ Type: Documentation-only [`fs.read()`]: fs.html#fs_fs_read_fd_buffer_offset_length_position_callback [`fs.readSync()`]: fs.html#fs_fs_readsync_fd_buffer_offset_length_position [`fs.stat()`]: fs.html#fs_fs_stat_path_options_callback -[`os.networkInterfaces`]: os.html#os_os_networkinterfaces [`os.tmpdir()`]: os.html#os_os_tmpdir [`process.env`]: process.html#process_process_env [`punycode`]: punycode.html diff --git a/doc/api/modules.md b/doc/api/modules.md index b032f168460c3e..66e0b9f32ddc83 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -905,6 +905,26 @@ by the [module wrapper][]. To access it, require the `Module` module: const builtin = require('module').builtinModules; ``` +### module.createRequire(filename) + + +* `filename` {string|URL} Filename to be used to construct the require + function. Must be a file URL object, file URL string, or absolute path + string. +* Returns: {[`require`][]} Require function + +```js +const { createRequire } = require('module'); +const requireUtil = createRequire(require.resolve('../src/utils/')); + +// Require `../src/utils/some-tool` +requireUtil('./some-tool'); +``` + ### module.createRequireFromPath(filename)