gpt4 book ai didi

string - 从内存中的字符串加载node.js模块

转载 作者:行者123 更新时间:2023-11-28 05:32:55 25 4
gpt4 key购买 nike

如果我将文件内容作为字符串存储在内存中,而不将其写入磁盘,我将如何 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/39558090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com