Skip to content

Commit be9a1ec

Browse files
gillesdemeytargos
authored andcommitted
module: allow passing a directory to createRequireFromPath
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]>
1 parent a0353fd commit be9a1ec

File tree

3 files changed

+31
-4
lines changed

3 files changed

+31
-4
lines changed

doc/api/modules.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -916,7 +916,7 @@ added: v10.12.0
916916

917917
```js
918918
const { createRequireFromPath } = require('module');
919-
const requireUtil = createRequireFromPath('../src/utils');
919+
const requireUtil = createRequireFromPath('../src/utils/');
920920

921921
// Require `../src/utils/some-tool`
922922
requireUtil('./some-tool');

lib/internal/modules/cjs/loader.js

+12-3
Original file line numberDiff line numberDiff line change
@@ -825,9 +825,18 @@ Module.runMain = function() {
825825
};
826826

827827
Module.createRequireFromPath = (filename) => {
828-
const m = new Module(filename);
829-
m.filename = filename;
830-
m.paths = Module._nodeModulePaths(path.dirname(filename));
828+
// Allow a directory to be passed as the filename
829+
const trailingSlash =
830+
filename.endsWith(path.sep) || path.sep !== '/' && filename.endsWith('\\');
831+
832+
const proxyPath = trailingSlash ?
833+
path.join(filename, 'noop.js') :
834+
filename;
835+
836+
const m = new Module(proxyPath);
837+
m.filename = proxyPath;
838+
839+
m.paths = Module._nodeModulePaths(m.path);
831840
return makeRequireFunction(m);
832841
};
833842

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use strict';
2+
3+
require('../common');
4+
const assert = require('assert');
5+
const path = require('path');
6+
7+
const { createRequireFromPath } = require('module');
8+
9+
const fixPath = path.resolve(__dirname, '..', 'fixtures');
10+
const p = path.join(fixPath, path.sep);
11+
12+
const req = createRequireFromPath(p);
13+
const reqFromNotDir = createRequireFromPath(fixPath);
14+
15+
assert.strictEqual(req('./baz'), 'perhaps I work');
16+
assert.throws(() => {
17+
reqFromNotDir('./baz');
18+
}, { code: 'MODULE_NOT_FOUND' });

0 commit comments

Comments
 (0)