简体   繁体   中英

Can I require a function in node.js without executing the entire required file?

This is the first time I ask a question here. I have the following example case: The export.js file contains a function and some extra lines of code. In this case, it's just a log:

//exporting.js
function add(a,b) {
return a+b;
}
console.log(add(5,8));
module.exports = add;

The import.js file requires the function add, but when it's executed it also prints the log in exporting.js

//import.js
adds = require('./exporting.js');
console.log(adds(1,2));

So it finally prints:

13
3

I want to know if there's a way to require a function without executing all the required file.

I've tried placing my function inside an object, but it still prints the first log.

I hope you can help me, I haven't find anything related, sorry if it's a noob question.

I want to know if there's a way to require a function without executing all the required file.

No, you cannot. With CommonJS modules, the only way you know what is exported is by running the file and letting it assign things to module.exports . Without running the file, there would be nothing exported.

The design solution for this would be to move the exported function you want into a separate module by itself where that module does nothing except export your function. Then, you can require() that module without any side effects of loading the module.

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