如果我将文件内容作为字符串存储在内存中,而不将其写入磁盘,我将如何 require() 文件?这是一个例子:
// Load the file as a string
var strFileContents = fs.readFileSync( "./myUnalteredModule.js", 'utf8' );
// Do some stuff to the files contents
strFileContents[532] = '6';
// Load it as a node module (how would I do this?)
var loadedModule = require( doMagic(strFileContents) );
最佳答案
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}', ''));
查看 module.js 中的 _compile、_extensions 和 _load
关于string - 从内存中的字符串加载node.js模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36682342/