Created
August 3, 2017 15:04
-
-
Save cb1kenobi/1fab5f65ff9dc292fbf710b6a5ffc5f1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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