true require() for code rather than file

If I have a string with source code in it

var code = "console.log('I've been loaded.');";

and want to run it in Node, normally it’s suggest to use

vm.runInThisContext(code, "NOT_A_FILE.mycode");

This is all well and good until the code becomes more complicated:

var code2 = "require('http');n" +
            "console.log(http);"  // TODO make more useless

In this case, we cannot
run code2 in vm
because it doesn’t let the module have a require()
function, as the vm is just a V8 VM, rather than a Node one.

This is the only problem I’ve run into so far—but I don’t know what other problems may be down the road.

So, fundamentally, my question is: what extra functionality does require()
do in making Node modules, and how can I ensure that my “string” modules have this functionality? If I need this functionality, am I better off just making temporary files which I actually require()
?

Problem courtesy of: Aaron Yodaiken

Solution

Please vm.runInNewContext
instead of vm.runInThisContext
, then runs it in sandbox and you can pass require object ! Thats it..

var vm = require('vm');
var code2 = "var http = require('http');n" + "console.log(http);" //TODO make more useless
vm.runInNewContext(code2, {
require: require,
http: require('http'),
console: console
}, 'yourvmfilename1');

OR you can directly send http object.

var vm = require('vm');
 var code3 = "console.log(http);" //TODO make more useless
 vm.runInNewContext(code3, {
 http: require('http'),
 console: console
}, 'yourvmfilename2');

Solution courtesy of: Amol M Kulkarni

稿源:Node.js Recipes (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » true require() for code rather than file

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录