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.