Modules and require() in NodeJS
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:
- Via a function
- 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;
