Skip to content

Commit c8e0983

Browse files
author
pooya parsa
committed
fix: use fake path if filename is directory
1 parent cff8c3d commit c8e0983

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

create-require.js

+16
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
const nativeModule = require('module')
22
const path = require('path')
3+
const fs = require('fs')
34

45
function createRequire (filename) {
6+
// If filename is dir, createRequire goes with parent directory, so we need fakepath
7+
if (isDir(filename)) {
8+
filename = path.join(filename, 'index.js')
9+
}
10+
511
// Added in Node v12.2.0
612
if (nativeModule.createRequire) {
713
return nativeModule.createRequire(filename)
@@ -25,4 +31,14 @@ function _createRequire (filename) {
2531
return mod.exports
2632
}
2733

34+
function isDir (path) {
35+
try {
36+
const stat = fs.lstatSync(path)
37+
return stat.isDirectory()
38+
} catch (e) {
39+
// lstatSync throws an error if path doesn't exist
40+
return false
41+
}
42+
}
43+
2844
module.exports = createRequire

test/test.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ const path = require('path')
22
const t = require('tap')
33
const createRequire = require('../create-require')
44

5-
const _require = createRequire(path.join(__dirname, 'some/index.js'))
5+
const _require = createRequire(path.join(__dirname, 'some'))
66
const e = _require('./file')
77
t.equal(e, 'someFile')
88
t.end()

0 commit comments

Comments
 (0)