Lesson 2 – Modules in NodeJS

Tram Ho

Built-in Modules and External Modules

As in the previous article I said: mỗi file đều được coi như là một module tách biệt . But basically, Modules in NodeJS will be divided into 2 types:

Build-in Modules:

These are the modules that NodeJS has built-in, meaning that you only need to install NodeJS to use them. You can see the list of modules here: https://www.w3schools.com/nodejs/ref_modules.asp

External Modules

With the list of Build-in Modules, it’s really little to support the dev code. It is the External Modules that create the true power for NodeJS. You can search this huge list of modules at https://www.npmjs.com/ or https://yarnpkg.com/ . Then the set through the statements. For example:

Caching

Does a module require many times, does it affect performance? The answer is you can require as many times as you want. When the app is run, the first require will be the time that the module is initialized and will be cached. The next require will check in the cache and use it, but will not initialize again.

But if you want the module to be excute many times, you can export it to a function, and when it’s time to call, you can call that function

Cycles

Now we will have 3 files as follows: step1.js

step2.js

server.js

If following the code, we will see that, when server.js is run, it will load step1.js , while step1.js loads step2.js again. At this time step2.js again loads step1.js . Thus, we will fall into an endless loop, right? It looks like that but NodeJS said no, we can’t do it here. To avoid this endless loop, an incomplete copy of step1.js will be exported and step2.js to step2.js . Then, when step2.js has finished loading, it will return data to step.js At that time, when running node server.js , we will get the following result

Today’s article stops here. Hopefully through this article, you can understand more about modules in NodeJS

Share the news now

Source : Viblo