简体   繁体   中英

How does requiring a module affect performance in Node.js?

I've been reading a few documentations on Node.js recently to try and get me started on some personnal work. During the process, a thought came up again and again, but I couldn't quite get a satisfactory answer.

In every piece of code I've seen so far, there were quite a few require(). I understand the primary function of it is to include modules. But it seems like people used it to include other Javascript files in their main, too. As far as I know, there is no proper way to do that in Javascript (as stated here: How do I include a JavaScript file in another JavaScript file? ).

Here is my concern; seperating files according to their functions is obviously good to improve readibility. However, isn't require() slowing down drastically the programm since it has to fetch information by opening the Javascript file and so on? If so, is the difference significant enough to worry about in a web application?

Wouldn't it be more prudent to write a programm that automates the assembly process in order to obtain a single file (or at least a more monolithic one) before submitting the version?

On the server, any performance impact here will be inconsequential relative to everything else the server is doing (like interpreting & executing all this javascript!). Of course, if you are having perf issues and are suspicious of this claim it's never a bad idea to measure.

On the other hand, if we're talking about javascript that will be sent over a network to a browser then it's a different story... there are a ton of tools for bundling & minifying code so browsers can download/execute it faster. That said, HTTP 2 changes this a bit - with this new protocol, many files can often be downloaded in parallel faster than big bundles.

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