Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
ncontext - run node.js script in the customer context
{
"curly": true,
"eqeqeq": true,
"immed": true,
"latedef": true,
"newcap": true,
"noarg": true,
"sub": true,
"undef": true,
"unused": "vars",
"boss": true,
"eqnull": true,
"node": true,
"trailing": true,
"strict": true,
"indent": 2,
"predef": [ "_context" ]
}
'use strict';
var vm = require('vm'),
path = require('path'),
fs = require('fs');
function runInContext(script, context) {
var scriptCtx, src, ctxFunc, ctxMod;
/* create a new context for the script */
scriptCtx = {
console: console,
_context: context
};
src = fs.readFileSync(script);
src = require('module').wrap(src);
try {
ctxMod = vm.createScript(src, script);
ctxFunc = ctxMod.runInNewContext(scriptCtx, script);
ctxFunc({}, require, module, path.basename(script), path.dirname(script));
}
catch (err) {
console.log('error: %s', err.toString());
}
}
(function () {
var testScript;
testScript = path.join(__dirname, 'test.js');
runInContext(testScript, 'context 1');
runInContext(testScript, 'context 2');
runInContext(testScript, 'context 3');
})();
'use strict';
(function () {
console.log('script in context: %s', _context);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment