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

标签 string node.js file require

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

相关文章:

C++ 将字符串日期 (1/4/2000) 转换为整数日期 (20000104)

ruby-on-rails - 如何在 Ruby 中划分字符串?

JavaScript:提取与正则表达式匹配的字符串

javascript - 使用 socket.io/node.js 上传文件 block 不适用于非文本文件

javascript - 如何正确地允许 Node js 有机会在我的无限 while 循环中运行其异步事件

c# - 查询 XML 文件并创建文本文件

c - 仅反转 C 中句子的顺序

node.js - 分离的子进程在 Node.js 中的脚本退出时退出

PHP 和并发文件访问

unix - 如何使用unix工具替换文件的最后一两个字符