Skip to content

Instantly share code, notes, and snippets.

@remarkablemark
Created August 22, 2016 19:51
Show Gist options
  • Select an option

  • Save remarkablemark/4a85c57c9c0175f3dc1eb365e7c20e6f to your computer and use it in GitHub Desktop.

Select an option

Save remarkablemark/4a85c57c9c0175f3dc1eb365e7c20e6f to your computer and use it in GitHub Desktop.
Node.js run module with a different `this` context.

Node.js run module with a different this context.

Sources:

// index.js

var vm = require('vm');
var fs = require('fs');
var path = require('path');

// create mock window
var jsdomify = require('jsdomify').default;
jsdomify.create();

// create context
var exports = {};
var context = window;
context.require = require;
context.console = console;
context.exports = exports;
context.module = { module: { exports: exports } };
context.window = window;

// run script in context
var script = fs.readFileSync(path.join(__dirname, './module'));
vm.runInNewContext(script, context);
// module.js

if (typeof window !== 'undefined' && this === window) {
    console.log('browser environment');
} else {
    console.log('node environment');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment