Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I avoid calling require when responding to a request?

Tags:

node.js

Is requireing a module going to block every single request? According to the docs, the module is cached after the first require but I wanted to see if it's an anti-pattern to do a dynamic require when responding to a request.

like image 954
Abdullah Jibaly Avatar asked Jan 24 '26 13:01

Abdullah Jibaly


1 Answers

Nope, it won't block on every request (as long as you're requiring the same module each time), and it's not an anti-pattern.

If you're loading the same module on each request, any call to require will return instantly (because the module will have already been loaded, compiled, and cached). If, however, many different modules may be required so that you don't get the benefit of caching, it may be better to do an asynchronous require.

But something like this?

function handler(req, res) { require('fs').readFile(…); }

No big deal. It's just a matter of style.

like image 198
Trevor Dixon Avatar answered Jan 26 '26 06:01

Trevor Dixon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!