Categories
JavaScript Answers

How to load a Node.js module from string in memory?

Spread the love

Sometimes, we want to load a Node.js module from string in memory.

In this article, we’ll look at how to load a Node.js module from string in memory.

How to load a Node.js module from string in memory?

To load a Node.js module from string in memory, we can use the require-from-string module.

To install it, we run

npm install require-from-string

Then we use it by writing

const requireFromString = require('require-from-string');

const m = requireFromString('module.exports = 1');

to call requireFromString with a string with the module’s code to require it.

As a result, m is 1.

Conclusion

To load a Node.js module from string in memory, we can use the require-from-string module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to load a Node.js module from string in memory?”

This post is like a video with a title “how to cook” and then you actually showing how to boil eggs in the video.

The most important real life use case of this would be if we can use a bundled js file. And this concept doesn’t work on a bundled file.

Leave a Reply

Your email address will not be published. Required fields are marked *