简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM