Load and Execute an javascript function in an External JS file using Node.js

98 Views Asked by At

I'd like to load and execute a Javascript function in external Javascript file using Node.js and similarly retrieve back with desired result after execution. Is it possible/not possible? If not, any other alternatives.

Any help regarding this is greatly appreciated.

1

There are 1 best solutions below

0
On

Yes, you can load another JS file as a module using Node.js module system and function require. There's quite good description of how to do it in Node.js documentation, take a look int this page.

Basically you have to load your external file calling function require and passing path to that file:

var externalFunction = require('./path/to/external/file')`;

but to make this work you have to export that function by writing something like

module.exports = functionToExport;

in your external file, where functionToExport is the name of the function which you want to use.