Modules and require() in NodeJS

Yasaa Moin
Aug 24, 2017 · 1 min read

In nodejs,when you out of curiousity trespass into the magical “node_modules” folder….you’re greeted by Classes,plentiful require() functions,some require() even have 2 sets of paranthesis,even constructors,and variables’ galore.Not to leave out “this” keywords too-especially if that file’s defining a Class.

So,here I’ll be aiding you with enough information to be able to make a little sense out of what you see .

First,there are plenty of ways to export a file — without thinking of the require() lets first just focus on the export.You can export functions inside a file individually.Say if this is familiar:

exports.sayHelloInEnglish = function() {
return "HELLO";
};


exports.sayHelloInSpanish = function() {
return "Hola";
};

Another way to export would be:

  1. Via a function
  2. Via a Class+Constructor

VIA A FUNCTION:

Example:

module.exports=function(app,db){

//whatever code written inside this is now publicly available wherever require() is used

//CRUD

//Create using app.post
app.post(‘/notes’,function(req,res){

});

//Read using app.get
app.get(‘/notes’,function(req,res){

});

//Update using app.put
app.put(‘/notes’,function(req,res){

});

//Delete using app.delete
app.delete(‘/notes’,function(req,res){

});

}

VIA A CLASS+CONSTRUCTOR:


const express = require(‘express’);

class Webserver { constructor(port)

{ this.port = port;

this.app = express();

this.server = require(‘http’).Server(this.app);

this.io = require(‘socket.io’)(this.server);

this.initVariables(); }

//now this will be followed by defining the functions above,in our case just //the initVariables()

//then

module.exports = Webserver;

)
Yasaa Moin

Written by

I enjoy reading articles,listening to audiobooks,philosophy,books . IG: @yasaamoin Twitter: @moinyasaa

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade