Created
March 7, 2018 03:16
-
-
Save jacintoface/66748623fb7ca00ee140921f0aa8ffd7 to your computer and use it in GitHub Desktop.
node编译字符串为模块
This file contains 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
function requireFromString(src, filename) { | |
var Module = module.constructor; | |
var m = new Module(); | |
m._compile(src, filename); | |
return m.exports; | |
} | |
console.log(requireFromString('module.exports = { test: 1}')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
function requireFromString(string, filename) {
const NativeModule = require('module')
var modules = { exports: {}}
const wrapper = NativeModule.wrap(string)
let strings = wrapper.substring(0,400)
console.log(strings, strings.length)
const script = new vm.Script(wrapper, {
filename: filename,
displayErrors: true
})
const result = script.runInThisContext()
result(modules.exports, require, modules, __filename, __dirname)
return module.exports
}
// 仿照nodejs源码方式利用vm编译字符串js