Node.js - Node Module System

What if we declare two functions in to different files with same name...? There is chances of overriding the one function with other. To avoid this , node introduced the module system where every file is treated as module. we cant access the content of one module from another module . Which remove the problem of overriding . Whenever we want to access the content of module we have to export . for example

Creating module with export

file1.js

var message=" hello world"

 function log(){
        console.log(message)
      } 
module.exports.log =log

module.exports.log =log
This syntax is used to export the module content .

Loading Module

index.js

const log = require("./file1.js")

Using require syntax we can load the exports of the file and use it.

Build in Node modules

There is build in modules which are listed on nodejs official website [nodejs.org/en/docs ] . In this section i am going to cover some of them.

  1. os module
const os=require('os')

const freemem=os.freemem()

console.log(freemem)

freemem return the free memory of the Os. There is lot of methods please refer the official document .

2.event module


const EventEmitter=require('events')

const emitter =new EventEmitter()

// This is event listener 
emitter.on(" logging msg" ,()=>{
console.log(" event listened....")
})

// This is event emit for disturbing or triggering  the event 
emitter.emit(" logging msg")

Event module returns the EventEmitter class ,then we created emitter the instance of that class. emit - method trigger the event on -event listener listen for the event and call the function

3.HTTP Module

This module is used to listen the Http request and respond on that req.

const http = require('http')

http.createServer(function(req,res){
if(req.url=="/"){
res.write("hello world )
}
})

http.listen(3000)

http behave like EventEmitter class .it also used to createserver which take callback function as argument with req and res parameter. we can run this program using node filename.js and then open the browser window with address [ localhost:3000 ].

thank u!