Permalink
Browse files

Initial commit

  • Loading branch information...
0 parents commit 86e654d0135804a566196946a1e638836e81f9f3 Mikito Takada committed Aug 17, 2011
Showing with 66 additions and 0 deletions.
  1. +36 −0 index.js
  2. +9 −0 package.json
  3. +21 −0 readme.md
@@ -0,0 +1,36 @@
+var vm = require('vm');
+var path = require('path');
+
+// From lib/module.js in the Node.js core (v.0.5.3)
+function stripBOM(content) {
+ // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
+ // because the buffer-to-string conversion in `fs.readFileSync()`
+ // translates it to FEFF, the UTF-16 BOM.
+ if (content.charCodeAt(0) === 0xFEFF) {
+ content = content.slice(1);
+ }
+ return content;
+}
+
+function runInContext(filename, sandbox) {
+ var content = require('fs').readFileSync(require.resolve(filename), 'utf8');
+ // remove shebang
+ content = stripBOM(content).replace(/^\#\!.*/, '');
+
+ // emulate require()
+ var self = { exports: {} };
+ for (var k in global) {
+ sandbox[k] = global[k];
+ }
+ sandbox.require = require;
+ sandbox.__filename = filename;
+ sandbox.__dirname = path.dirname(filename);
+ sandbox.module = self;
+ sandbox.exports = self.exports;
+ sandbox.global = sandbox;
+
+ vm.runInNewContext(content, sandbox);
+ return sandbox.exports;
+}
+
+module.exports = runInContext;
@@ -0,0 +1,9 @@
+{
+ "name": "requireInContext",
+ "description": "Wrapper to require() js files in a custom context",
+ "version": "0.0.1",
+ "author": "Mikito Takada <mixu@mixu.net>",
+ "keywords": ["require"],
+ "repository": "git://github.com/mixu/requireincontext",
+ "main": "index.js"
+}
@@ -0,0 +1,21 @@
+# RequireInContext
+
+Allows you to do a require() with a custom context.
+
+Useful for emulating a browser environment in Node:
+
+ var requireInContext = require('runincontext');
+ var myclient = requireInContext('./myclient.js', {
+ window: {},
+ io: require('socket.io')
+ });
+
+Or for specifying mock objects for running tests:
+
+ var requireInContext = require('runincontext');
+ var mycode = requireInContext('./mycode.js', {
+ mydependency: require('./dependency_mock.js')
+ });
+
+
+

0 comments on commit 86e654d

Please sign in to comment.