从内存中的字符串加载 node.js 模块 [英] Load node.js module from string in memory

查看:24
本文介绍了从内存中的字符串加载 node.js 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将文件的内容作为字符串保存在内存中,而不将其写到磁盘,我将如何 require() 文件?举个例子:

How would I require() a file if I had the file's contents as a string in memory, without writing it out to disk? Here's an example:

// 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

这篇关于从内存中的字符串加载 node.js 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆