|
23 | 23 |
|
24 | 24 | const { NativeModule } = require('internal/bootstrap/loaders'); |
25 | 25 | const util = require('util'); |
26 | | -const { pathToFileURL } = require('internal/url'); |
| 26 | +const { pathToFileURL, fileURLToPath, URL } = require('internal/url'); |
27 | 27 | const vm = require('vm'); |
28 | 28 | const assert = require('assert').ok; |
29 | 29 | const fs = require('fs'); |
@@ -834,12 +834,48 @@ Module.runMain = function() { |
834 | 834 | process._tickCallback(); |
835 | 835 | }; |
836 | 836 |
|
837 | | -Module.createRequireFromPath = (filename) => { |
838 | | - const m = new Module(filename); |
839 | | - m.filename = filename; |
840 | | - m.paths = Module._nodeModulePaths(path.dirname(filename)); |
| 837 | +function createRequireFromPath(filename) { |
| 838 | + // Allow a directory to be passed as the filename |
| 839 | + const trailingSlash = |
| 840 | + filename.endsWith(path.sep) || path.sep !== '/' && filename.endsWith('\\'); |
| 841 | + |
| 842 | + const proxyPath = trailingSlash ? |
| 843 | + path.join(filename, 'noop.js') : |
| 844 | + filename; |
| 845 | + |
| 846 | + const m = new Module(proxyPath); |
| 847 | + m.filename = proxyPath; |
| 848 | + |
| 849 | + m.paths = Module._nodeModulePaths(path.dirname(proxyPath)); |
841 | 850 | return makeRequireFunction(m); |
842 | | -}; |
| 851 | +} |
| 852 | + |
| 853 | +Module.createRequireFromPath = createRequireFromPath; |
| 854 | + |
| 855 | +const createRequireError = 'must be a file URL object, file URL string, or' + |
| 856 | + 'absolute path string'; |
| 857 | + |
| 858 | +function createRequire(filename) { |
| 859 | + let filepath; |
| 860 | + if (typeof filename === 'object' && !(filename instanceof URL)) { |
| 861 | + throw new ERR_INVALID_ARG_VALUE('filename', filename, createRequireError); |
| 862 | + } else if (typeof filename === 'object' || |
| 863 | + typeof filename === 'string' && !path.isAbsolute(filename)) { |
| 864 | + try { |
| 865 | + filepath = fileURLToPath(filename); |
| 866 | + } catch { |
| 867 | + throw new ERR_INVALID_ARG_VALUE('filename', filename, |
| 868 | + createRequireError); |
| 869 | + } |
| 870 | + } else if (typeof filename !== 'string') { |
| 871 | + throw new ERR_INVALID_ARG_VALUE('filename', filename, createRequireError); |
| 872 | + } else { |
| 873 | + filepath = filename; |
| 874 | + } |
| 875 | + return createRequireFromPath(filepath); |
| 876 | +} |
| 877 | + |
| 878 | +Module.createRequire = createRequire; |
843 | 879 |
|
844 | 880 | Module._initPaths = function() { |
845 | 881 | const isWindows = process.platform === 'win32'; |
|
0 commit comments