Categories
JavaScript Answers

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

Spread the love

To load and execute external JavaScript file in Node.js with access to local variables, we create a module with the variables and require the module.

For instance, we write

const PI = 3.14;

exports.area = (r) => {
  return PI * r * r;
};

exports.circumference = (r) => {
  return 2 * PI * r;
};

in circle.js to export the area and circumference functions.

Then we write

const circle = require("./circle");
console.log(circle.area(4));

to require the circle.js file and call the area function from circle.js.

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 *