Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load node.js module from string in memory

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) ); 
like image 795
ZECTBynmo Avatar asked Jul 10 '13 22:07

ZECTBynmo


People also ask

How do I load a node JS module?

Loading Core Modules In order to use Node. js core or NPM modules, you first need to import it using require() function as shown below. var module = require('module_name'); As per above syntax, specify the module name in the require() function.

How are node modules loaded?

Modules are the building block of any node application and are loaded by using require statement or import statement if you are using ES6 Javascript code. program. of the one saved under /Users/Max/node_modules for example. included in your app.

Does NodeJS cache modules?

From the node. js documentation: Modules are cached after the first time they are loaded.


1 Answers

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}', '')); 

look at _compile, _extensions and _load in module.js

like image 92
Andrey Sidorov Avatar answered Oct 06 '22 13:10

Andrey Sidorov