gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:54:19 27 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/17581830/

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