Skip to content

Instantly share code, notes, and snippets.

@cb1kenobi
Created August 3, 2017 15:04
Show Gist options
  • Save cb1kenobi/1fab5f65ff9dc292fbf710b6a5ffc5f1 to your computer and use it in GitHub Desktop.
Save cb1kenobi/1fab5f65ff9dc292fbf710b6a5ffc5f1 to your computer and use it in GitHub Desktop.
const vm = require('vm');
const wrap = require('module').wrap;
const code = `module.exports = {
foo: function () {
register(ctx => {
if (ctx.i === 0) {
throw new TypeError('boom');
}
if (ctx.i === 1) {
console.log(ctx.data.blah);
}
});
}
};`;
const ctx = { exports: {} };
let fn;
const globalObj = {
register(handler) {
fn = handler;
},
console: console
};
const compiled = vm.runInNewContext(wrap(code), globalObj, {
filename: 'foobar.js',
lineOffset: 0,
displayErrors: false
});
compiled.apply(ctx.exports, [
ctx.exports,
require,
ctx,
'foobar.js',
__dirname
]);
ctx.exports.foo();
try {
fn({ i: 0 });
console.log('it worked');
} catch (err) {
console.error('error!', err);
console.log(err instanceof Error);
}
try {
fn({ i: 1 });
console.log('it worked');
} catch (err) {
console.error('error!', err);
console.log(err instanceof Error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment