Categories
JavaScript Answers

How to load and execute external JavaScript file in Node.js with access to local variables?

Spread the love

Sometimes, we want to load and execute external JavaScript file in Node.js with access to local variables.

In this article, we’ll look at how to load and execute external JavaScript file in Node.js with access to local variables.

How to load and execute external JavaScript file in Node.js with access to local variables?

To load and execute external JavaScript file in Node.js with access to local variables, we can use the vm module.

For instance, we write

const vm = require("vm");
const fs = require("fs");

const data = fs.readFileSync("./externalfile.js");
const script = new vm.Script(data);
script.runInThisContext();

to read the externfile.js JavaScript file with readFileSync.

Then we create a vm.Script object with the read file.

Next, we call runInThisContext to run the script file.

Conclusion

To load and execute external JavaScript file in Node.js with access to local variables, we can use the vm module.

By John Au-Yeung

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

Leave a Reply

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