Sitemap

Node Module System

3 min readJun 24, 2018

--

node Modules examples : os, fs, events, http

Get Hasitha Madusanka’s stories in your inbox

Join Medium for free to get updates from this writer.

What Modules are?

  • In Node we don’t have window object instead we have another object called global. All the inbuilt functions can be accessed by via global object.
figure 01
  • Not like client side JavaScript the variable define in scope using var not gonna added to global object. (output gonna be undefined). They are only scope to in this file so they are not gonna available outside of this file. This is because of Node modular system.
figure 02
  • Why Node things(functions and variables) not added to global scope like client side JavaScript. Because client side JavaScript behavior has a problem which is each and every function add to global scope and cause to override functions and variables that has same names. In order to build reliable and maintainable applications we should avoid defining variables and function in the global scope. Instead we need modularity.

Why we need Modules?

  • We need to create small building blocks or modules so two functions or variables with same name won’t override each other. Every file in node application as considers as module. The variables and functions define in that file or that module is scoped to that file.
  • In OOP terms we say they are private. If you want to access variable define module from outside from a module you need to explicitly export it and make it public.
  • In Node module has at least one file or one module which we called main module.

How Modules works?

  • What is in node module object. id: Every module has , filename: compete path to that file, loaded: module loaded or not, .. etc. you will gradually familiar with this object.
Press enter or click to view image in full size
figure 03

How to create and import modules?

Press enter or click to view image in full size
figure 04
  • figure 04 shows how to create module and how to import it. import it to other module it get single object using it’s variable you can access functions. This is how modules can work in Node.
  • better we can store import objects into constant because we can accidentally override the value of logger from another value.

--

--

Hasitha Madusanka
Hasitha Madusanka

Written by Hasitha Madusanka

Software Engineer at Empite Pty Ltd.