| 1 |
// Require module in given context |
| 2 |
|
| 3 |
"use strict"; |
| 4 |
|
| 5 |
var validValue = require("es5-ext/object/valid-value") |
| 6 |
, Module = require("module") |
| 7 |
, readFileSync = require("fs").readFileSync |
| 8 |
, path = require("path") |
| 9 |
, vm = require("vm") |
| 10 |
, memoize = require("memoizee") |
| 11 |
, isModuleNotFoundError = require("ncjsm/is-module-not-found-error"); |
| 12 |
|
| 13 |
var dirname = path.dirname |
| 14 |
, extname = path.extname |
| 15 |
, objHasOwnProperty = Object.prototype.hasOwnProperty |
| 16 |
, natives = process.binding("natives") |
| 17 |
, wrap = Module.wrap; |
| 18 |
|
| 19 |
var get = memoize(function (modulePath) { return new Module(modulePath, module); }, { length: 2 }); |
| 20 |
|
| 21 |
module.exports = exports = function (modulePath, context /*, options*/) { |
| 22 |
var options = arguments[2] || {}; |
| 23 |
var fmodule, content, dirpath; |
| 24 |
|
| 25 |
validValue(context); |
| 26 |
if (context === global) { |
| 27 |
try { |
| 28 |
return require(modulePath); |
| 29 |
} catch (error) { |
| 30 |
if (options.isSilent && isModuleNotFoundError(error, modulePath)) return null; |
| 31 |
throw error; |
| 32 |
} |
| 33 |
} |
| 34 |
if (objHasOwnProperty.call(natives, modulePath)) return require(modulePath); |
| 35 |
fmodule = get(modulePath, context); |
| 36 |
if (fmodule.loaded) return fmodule.exports; |
| 37 |
fmodule.filename = modulePath; |
| 38 |
dirpath = dirname(modulePath); |
| 39 |
fmodule.paths = Module._nodeModulePaths(dirpath); |
| 40 |
fmodule.require = function (targetPath) { |
| 41 |
return exports(Module._resolveFilename(String(targetPath), this), context); |
| 42 |
}; |
| 43 |
try { |
| 44 |
content = readFileSync(modulePath, "utf8"); |
| 45 |
} catch (e) { |
| 46 |
if (e.code === "ENOENT") { |
| 47 |
if (options.isSilent) return null; |
| 48 |
throw new Error("Cannot find module '" + modulePath + "'"); |
| 49 |
} |
| 50 |
throw e; |
| 51 |
} |
| 52 |
fmodule.loaded = true; |
| 53 |
if (extname(modulePath) === ".json") { |
| 54 |
fmodule.exports = JSON.parse(content); |
| 55 |
} else { |
| 56 |
vm.runInContext(wrap(content), context, modulePath).call( |
| 57 |
fmodule.exports, fmodule.exports, fmodule.require.bind(fmodule), fmodule, modulePath, |
| 58 |
dirpath |
| 59 |
); |
| 60 |
} |
| 61 |
return fmodule.exports; |
| 62 |
}; |