What is Nodejs modules?

Konfinity
March 2,2021 - 6 min read
What is Nodejs modules?

Modules in Nodejs are very similar to JavaScript libraries. A module is a group of functions that the developer wants to include in a Nodejs application. Modules can be reused throughout the application. Modules do not interfere with other modules as each of them has their own context and are placed in a separate Javascript file inside a separate folder. In Nodejs, there are three types of modules, that is, core, local and third part modules.

The Node.js core modules have bare minimum functionalities of Node.js. As soon as Nodejs starts, the core modules are compiled into its binary distribution and load automatically. Developers just need to import core module so that it can be used in applications. Some of the most common yet important core modules in Nodejs are -.

Another type of Nodejs modules is the local ones. Local modules in Nodejs are created locally in one particular Node.js application. The different functionalities of the application are contained in separate files and folders of the local modules in Nodejs. The local modules in Nodejs can be packaged and distributed via the Node Package Manager. This packaging and distributing makes it possible for the Node.js community to use those local modules. For example, a module can be created to connect and fetch data from a database. This particular module can also be reused in the entire application

The third type we mentioned is the third party module. These third type modules can be downloaded with the help of a Node Package Manager. Basically, these modules are called third party modules because they are developed by the community and can be used by anybody for their project. Some examples of third part modules include express, gulp, lodash, debug, react, mocha among others. These modules are installed inside a particular project folder or can also be installed globally.

Now that we read about the basic concept and broad types of Nodejs modules, let’s discuss them in more detail.

Modules in Nodejs

Before talking about the different concepts and utilities of Modules, let’s understand how to include modules in your Nodejs. The require () function is used to include a module in your Nodejs projects. The name of the module has to be included in the require () function. The syntax of the same would be var url = require(url);

Creating Modules

There are built-in modules in Nodejs, however, you can also create your own modules and include them in your Nodejs applications. Let’s understand how to create your own module with the help of an example. In this example, we will create a module that returns a date and time object.

  • exports.myDateTime = function () {
  • return Date();
  • } ;

The keyword ‘export’ is used to make the properties and methods available outside of the module file. Now that we have created our very own module, it’s time to use it in the actual Nodejs project.

As a first step, you have saved the particular code with a name of your choice and a javascript extension. In this example, we will save the code with name "ownmodule.js". This module has to be now included in the Node.js files. Let’s look at the example below in order to understand how to include your customised module in the Nodejs file.

The code to use the module "ownmodule" in a Node.js file would look like -

  • var konfinity = require('./ownmodule');
  • http.createServer(function (req, res) {
  • res.writeHead(200, {'Content-Type': 'text/html'});
  • res.write("Right now, the date and time are " + dt.myDateTime());
  • res.end();
  • }).listen(8080);

In the code above, ./ is used to locate the module. It referes that the module the user created is present in the same folder as the Node.js file

Built-in Modules

There are a few built-in modules in Nodejs. The advantage of built-in modules is that developers can use them without any further installation. Some of the Built-in Modules in Nodejs are assert, buffer, http, https, url among others. We are going to talk about some of these modules in detail. Let’s start by talking about the HTTP module.

HTTP Module

The HTTP or the Hyper Text Transfer Protocol Module in Nodejs is a built-in one. It allows the transfer of data over HTTP in any Nodejs application. As mentioned above, we will use the require () method to include the HTTP module.

URL Module

Another built-in Module in Nodejs is the URL module. This module basically splits up a web address into different readable parts. Let’s understand the URL module with the help of an example.

The first step is to include the URL module with the help of the require () method. We have mentioned the syntax of the require () method earlier in the blog. The next step is to use the url.parse () method to parse an address. This will return a URL object. The web address is basically split into parts that are readable by the common audience.

File System Module

This module, as the name suggests, enables developers to work with the file system on its computers. The require () method is used to include the File System module. Some of the most common uses of this module is to create, read, update, delete, rename or read files. For example, the function fs.readFile() is used to read files on the computer. There are a bunch of methods used for creating new files are fs.appendFile (), fs.open (), fs.writeFile ().

The first method is used to, as the name suggests, append the given file. Also, if one particular file is appended but does not exist then a file of the same name will be created. The syntax of fs.appendFile () would look something like -

  • fs.appendFile('newfile.txt', 'Hello Konfinity!', function (err) {
  • if (err) throw err;
  • console.log('Done!');
  • });

The next method to discuss is the fs.open() method. This method takes a "flag" as the second argument. If the flag is "w", the specified file is opened for writing and if the called file does not exist then an empty file is created. The syntax of the fs.open() method will look like

  • fs.open('newfile2.txt', 'w', function (err, file) {
  • if (err) throw err;
  • console.log('Done!');
  • });

If you want to replace a particular file and its contents then the fs.writeFile() method is used. Also, if the file doesn’t already exist, a new one will be created.

  • fs.writeFile('newfile3.txt', 'Hello Konfinity!', function (err) {
  • if (err) throw err;
  • console.log('Saved!');
  • });

Apart from these methods included in the file system module of Nodejs, there are a couple of other methods included too. Let’s look at some of them and understand the concept in detail. The methods generally used to update files in a system are fs.appendFile() and fs.writeFile().

fs.appendFile() is a method that appends particular content at the end of the file mentioned in the code. The syntax for the method fs.appendFile() would look like –

  • fs.appendFile('newfile1.txt', ' This is my text.', function (err) {
  • if (err) throw err;
  • console.log('Updated!');
  • });

This code would append the text "Welcome to Konfinity" to the end of the file that goes by the name "newfile1.txt".

Another method is the fs.writeFile() one which replaces the file and content mentioned in the code. The syntax of the methh

  • fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {
  • if (err) throw err;
  • console.log('Replaced!');
  • });

The code above replaces the content of the file "newfile3.txt": There are methods to delete files too. The fs.unlink() method is used to delete a particular file with the File System module. The syntax of this method will look like –

  • fs.unlink('newfile2.txt', function (err) {
  • if (err) throw err;
  • console.log ('File deleted!');
  • });

The code basically deletes the file "newfile2.txt":

In Nodejs, developers can also upload files to their computer. Apart from this, the file system module can also be use to rename files. The fs.rename() method is used to rename a file. This method renames the file mentioned in the code, the syntax for the same will look like -

  • fs.rename('Konfinity.txt', 'Konfinity1.txt', function (err) {
  • if (err) throw err;
  • console.log('File Renamed!');
  • });

The code above, renames the file "Konfinity.txt" to "Konfinity1.txt":

Also keep in mind that all the methods mentioned above is prefixed with a variable fs. In these examples above, we took the variable to be ‘fs’, while executing your code, you would have to explicitly mention it in your code. The code will look something like - var fs = require('fs');

With this, we come to an end of this brief explanation of modules in Nodejs. We hope that the explanation was clear and you have understood the concept of Nodejs modules. If you have any doubts or queries hovering around your head, please feel free to contact us!

Also, if you wish to start your journey in web development, we have something very interesting for you. There is a professional web development course that will address all your concerns regarding web development and help you ace your skills. Make sure you check out the course that can be a stepping stone to your dream of becoming a proficient web developer.

Out of the many available, the course that we recommend would be Konfinity’s Web Development Course The course is well-researched and is one of the most beneficial training courses out there. It is developed by experts from IIT DELHI in collaboration with tech companies like Google, Amazon and Microsoft. It is trusted by students and graduates from IIT, DTU, NIT, Amity, DU and more.

We encourage technocrats like you to join the course to master the art of creating web applications by learning the latest technologies, right from basic HTML to advanced and dynamic websites, in just a span of a few months.

Konfinity is a great platform for launching a lucrative tech career. We will get you started by helping you get placed in a high paying job. One amazing thing about our course is that no prior coding experience is required to take up our courses. Start your free trial here.

Chat with us