diff options
author | Johannes Ewald <mail@johannesewald.de> | 2013-02-23 17:52:22 +0400 |
---|---|---|
committer | Johannes Ewald <mail@johannesewald.de> | 2013-02-23 17:52:22 +0400 |
commit | 6040974a2f0bc91b3aed0a389584c967831dd1dd (patch) | |
tree | 6fe8a1c3aaafaf7a7aca989e369ca38222498d82 /lib/rewire.js | |
parent | 5fcb70fd718abc7b3f556932c68f7d3a3cbcde34 (diff) |
- added Coffee-Script support closes #8 (jashkenas/coffee-script#2707)
- renamed internalRewire.js to simply rewire.js
- moved all the stuff related to manipulating the module environment to moduleEnv.js
Diffstat (limited to 'lib/rewire.js')
-rw-r--r-- | lib/rewire.js | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/lib/rewire.js b/lib/rewire.js new file mode 100644 index 0000000..3556533 --- /dev/null +++ b/lib/rewire.js @@ -0,0 +1,56 @@ +var Module = require("module"), + fs = require("fs"), + __get__ = require("./__get__.js"), + __set__ = require("./__set__.js"), + getImportGlobalsSrc = require("./getImportGlobalsSrc.js"), + detectStrictMode = require("./detectStrictMode.js"), + moduleEnv = require("./moduleEnv.js"); + +/** + * Does actual rewiring the module. For further documentation @see index.js + */ +function internalRewire(parentModulePath, targetPath) { + var targetModule, + prelude, + appendix, + src; + + // Checking params + if (typeof targetPath !== "string") { + throw new TypeError("Filename must be a string"); + } + + // Resolve full filename relative to the parent module + targetPath = Module._resolveFilename(targetPath, parentModulePath); + + // Special support for older node versions that returned an array on Module._resolveFilename + // @see https://github.com/joyent/node/blob/865b077819a9271a29f982faaef99dc635b57fbc/lib/module.js#L319 + // TODO Remove this switch on the next major release + if (Array.isArray(targetPath)) { + targetPath = targetPath[1]; + } + + // Create testModule as it would be created by require() + targetModule = new Module(targetPath, parentModulePath); + + // We prepend a list of all globals declared with var so they can be overridden (without changing original globals) + prelude = getImportGlobalsSrc(); + + // We append our special setter and getter. + appendix = "module.exports.__set__ = " + __set__.toString() + "; "; + appendix += "module.exports.__get__ = " + __get__.toString() + "; "; + + // Check if the module uses the strict mode. + // If so we must ensure that "use strict"; stays at the beginning of the module. + src = fs.readFileSync(targetPath, "utf8"); + if (detectStrictMode(src) === true) { + prelude = ' "use strict"; ' + prelude; + } + + moduleEnv.inject(prelude, appendix); + moduleEnv.load(targetModule); + + return targetModule.exports; +} + +module.exports = internalRewire;
\ No newline at end of file |