
Node.JS Modules & Exports
What are modules?
A module in NodeJS is a simple or complex JavaScript file which can be used throughout your web app. In short, each module is just a file with JavaScript code in it.
There are three types of modules:
Core Modules:
These type of modules include bare minimum functionalities in Node.JS. Common examples can be:
http : to build a simple HTTP server paths : to deal with file paths fs : work with simple file input/output operations
Local Modules
These are the modules built by you: the programmer.
It’s good practice to write modules as it promotes cleanliness of your code and make your code modular(you can reuse your module in other projects without a lot of additional effort)
Third Party Modules
These types of modules are built by the programming community. They mostly include complex code so that the programmer can add functionality to his app without writing it himself. This way, he saves time as well.
How can I use these modules?
When using modules, you simply use the function require()
const myModule = require("moduleName")Example:
Lets use fs (file system module) to read a simple text file as an example:
Open notepad, write any piece of text on it and then save it anywhere. Let’s name it “demofile.txt”. Open your code editor and write this piece of code and save it as the same directory as your .txt file:
const fs = require("fs")
fs.readFile("demofile.txt" , {encoding : 'utf-8'} , function(err,data) {
if(err) console.log(err)
console.log(data)
})now save it as “fsExample.js” and run it on your command line
node fsExample(For more details on running your code through your command line, I’ve written a guide)
As a result, you’ll see the contents of your text file printed out
Details of the readFile method:
The first parameter is the name of the text file you wish to read
Second parameter is your options : here, encoding method is ‘utf-8’ so that text can be printed out. If you don’t specify the options, it will print out buffer values, which are unreadable to humans.
Third parameter is the callback function. What are callback functions? Learn about them here . First we check whether there are errors(maybe error in reading file or etc.) and then print them out if they are present, otherwise the contents of the file are printed out if everything’s okay.
Using Third Party Modules
First install a module through npm
Lets install express as an example
npm i expressThen require() like so:
const express = require('express')Note: I’ve written a basic guide for NPM, see here
Using local modules
To use your own modules(local modules) , you have to ‘export’ it first. You can export strings, functions , variables etc.
Syntax is as follows:
module.exports = <Object to be exported> The most simple example
Create a module called ‘message.js’ and another called ‘app.js’ .
message.js
module.exports = "Hello World" app.js
const message = require('./message.js')
console.log(message)Run the code app.js on the command line. As a result, “Hello World” will be printed out.
To export a function, the code is similar:
message.js
module.exports = function() {
console.log("Hello World")
}app.js
const message = require("./message.js")
message();Exports object
exports is an object. Thus , you can add properties to it. module.exports
message.js
module.exports.sayHello = function() {
console.log('Hello')
}module.exports.sayCustomMessage = function(message) {
console.log(message)
}
module.exports.myVariable = 4
module.exports = {
firstName: 'Hussain'
lastName: 'Arif'
}app.js
const message = require('./message.js')
message.sayHello()
message.sayCustomMessage('Goodbye!');
console.log(message.myVariable)
console.log(message.firstName + ' ' + message.lastName)In summary, to use local modules: 1) use module.exports to export it 2) use require() to use its functionality.
The require method can be used to import:
const filesystem = require('fs') // core moduleconst express = require('express') // npm moduleconst server = require('./boot/server.js') // server.js file with a relative path down the treeconst server = require('../boot/server.js') // server.js file with a relative path up the treeconst server = require('/var/www/app/boot/server.js') // server.js file with an absolute pathconst server = require('./boot/server') // file if there's the server.js fileconst routes = require('../routes') // index.js inside routes folder if there's no routes.js fileconst databaseConfigs = require('./configs/database.json') // JSON fileNote: To require a third party/NPM module do not include “.” or “..” in your parameters.The modules will already be present in the “node_modules” directory located in your project
That’s all for today. See you later!
Stay home, save lives.