Module System - Node JS

Module System - Node JS

Module System for Beginners

Anirudh Panda
·Aug 14, 2021·

5 min read

Subscribe to my newsletter and never miss my upcoming articles

Node.js is a JavaScript run-time built on top of the Chrome v8 engine. Succinctly, Node.js as a platform provides an environment outside of the traditional web browser for executing JavaScript code (It's important to note here that Node.js was created for building network applications using JavaScript).

node1.png

The best way to get started with Node.js is to explore its module system. The module system lets you load external libraries into your application. That’ll enable you to take advantage of built-in Node.js modules as well as third-party npm modules. This includes libraries for connecting to databases, creating web servers, and more!

Node.js comes with dozens of built-in modules. These built-in modules sometimes referred to as core modules, give you access to tools for working with the file system, making HTTP requests, creating web servers, and more! In this lesson, you’ll learn how to load in those core modules and use them in your code.

Types of Node Js Modules ✔

We can place Node.js modules into three categories:

  • Built-in modules: These are modules that come with Node.js itself; you don't have to install them separately.
  • Local modules: These are modules that you have created within your application.
  • Third-party modules: When you install Node.js, you also get npm. npm is a package manager that allows you to install and use third-party npm libraries in your code.

BUILT-IN MODULES ✨

Node.js comes with dozens of built-in modules. These built-in modules, sometimes referred to as core modules, give you access to tools for working with the file system, making HTTP requests, creating web servers, and more!

The module system is built around the require function. This function is used to load in a module and get access to its contents. require is a global variable provided to all your Node.js scripts, so you can use it anywhere you like!

const fs = require('fs')
fs.writeFileSync('name.txt', 'My name is Anirudh')

The script above uses require to load in the fs module. This is a built-in Node.js module that provides functions you can use to manipulate the file system. The script uses writeFileSync to write a message to name.txt. After you run the script, you’ll notice a new name.txt file in your directory. Open it up and you’ll see, “My name is Anirudh”.

Few important methods of the fs module are :

  1. Use fs.readFileSync() method to read the physical file synchronously. fs.readFileSync(path[, options])
  2. Use fs.writeFileSync() method to write data to a file. If the file already exists then it overwrites the existing content otherwise it creates a new file and writes data into it. fs.writeFileSync(file, data[, options])
  3. Use fs.appendFile() method to append the content to an existing file. fs.appendFileSync(path, data[, options])
  4. Use fs.open() method to open a file for reading or writing. fs.open(path, flags[, mode], callback)
  5. Use fs.unlink() method to delete an existing file. fs.unlink(path, callback);

LOCAL MODULES 🎊

You know how to use require to load in built-in modules. require can also be used to load in JavaScript files you’ve created. All you need to do is provide require with a relative path to the script you want to load. This path should start with ./ and then link to the file that needs to be loaded in.

const add = require('./sum.js')
const sum = add(60, 9)
console.log(sum);

The code above uses require to load in a file called sum.js in the src directory. It stores the module contents in a variable, and then use the contents in the script.

Node.js provides the required script with a place to store values that should be exported as part of the library. This is on module.exports. You can see sum.js below. A function is defined and then assigned to module.exports. The value stored on module.exports will be the return value for require when the script is imported.

const add = function (a, b) {
  return a + b;
};
module.exports = add;

If you run the original script, you’ll see the message that logged from the add function in sum.js.

node app.js
69

Your Node.js scripts don’t share a global score. This means variables created in one script are not accessible in a different script. The only way to share values between scripts is by using require with module.exports.

THIRD-PARTY MODULES 🎇

Node Package Manager (npm) is the package manager for JavaScript and the world's largest software registry, enabling developers to discover packages of reusable code.

Initializing npm :-

Your Node.js application needs to initialize npm before npm can be used. You can run npm init from the root of your project to get that done. That command will ask you a series of questions about the project and it’ll use the information to generate a package.json file in the root of your project. Here's an example:

{
 "name": "sum-app",
 "version": "1.0.0",
 "description": "",
 "main": "app.js",
 "scripts": {
 "test": "echo \"Error: no test specified\" && exit 1"
 },
 "author": "",
 "license": "ISC",
}

Installing an npm Module :-

To install an npm package, you only need to run the command npm install <package-name> within your project directory.

Let's look at an example. If we wanted to use a package like chalk in our project, we could run the following command on our Command-Line, within our project directory: npm install chalk

This command does three important things:

  1. It creates a node_modules directory. npm uses this directory to store all the code for the npm modules you have installed.
  2. npm adds the module as a dependency by listing it in the dependencies property in package.json. This allows you to track and manage the module you have installed.
  3. npm creates a package-lock.json file. This includes detailed information about the modules you’ve installed which helps keep things fast and secure.

You should never make changes to node_modules or package-lock.json. Both are managed by npm and will get changed as you run npm commands from the terminal.

To load in an npm module, pass the npm module name to require.

const chalk = require("chalk");

console.log(chalk.yellow("Hello world!"));

We will get a yellow-colored Hello world! in our command line

That's It, Folks!!

In our first blog, we understood how the module system works in Node.js and what are its types and uses.

PS: I am currently learning node js and in sync writing these articles, if any information seems incorrect please don't hesitate to reach out!!

Did you find this article valuable?

Support Anirudh Panda by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this

Impressum

Limitless