Skip to content

Commit

Permalink
module: allow passing a directory to createRequireFromPath
Browse files Browse the repository at this point in the history
Fixes: #23710

PR-URL: #23818
Reviewed-By: Guy Bedford <[email protected]>
Reviewed-By: Myles Borins <[email protected]>
Reviewed-By: Ruben Bridgewater <[email protected]>
Reviewed-By: Anna Henningsen <[email protected]>
  • Loading branch information
gillesdemey authored and targos committed May 4, 2019
1 parent a0353fd commit be9a1ec
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
2 changes: 1 addition & 1 deletion doc/api/modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -916,7 +916,7 @@ added: v10.12.0

```js
const { createRequireFromPath } = require('module');
const requireUtil = createRequireFromPath('../src/utils');
const requireUtil = createRequireFromPath('../src/utils/');

// Require `../src/utils/some-tool`
requireUtil('./some-tool');
Expand Down
15 changes: 12 additions & 3 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -825,9 +825,18 @@ Module.runMain = function() {
};

Module.createRequireFromPath = (filename) => {
const m = new Module(filename);
m.filename = filename;
m.paths = Module._nodeModulePaths(path.dirname(filename));
// Allow a directory to be passed as the filename
const trailingSlash =
filename.endsWith(path.sep) || path.sep !== '/' && filename.endsWith('\\');

const proxyPath = trailingSlash ?
path.join(filename, 'noop.js') :
filename;

const m = new Module(proxyPath);
m.filename = proxyPath;

m.paths = Module._nodeModulePaths(m.path);
return makeRequireFunction(m);
};

Expand Down
18 changes: 18 additions & 0 deletions test/parallel/test-module-create-require-from-directory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';

require('../common');
const assert = require('assert');
const path = require('path');

const { createRequireFromPath } = require('module');

const fixPath = path.resolve(__dirname, '..', 'fixtures');
const p = path.join(fixPath, path.sep);

const req = createRequireFromPath(p);
const reqFromNotDir = createRequireFromPath(fixPath);

assert.strictEqual(req('./baz'), 'perhaps I work');
assert.throws(() => {
reqFromNotDir('./baz');
}, { code: 'MODULE_NOT_FOUND' });

0 comments on commit be9a1ec

Please sign in to comment.