Node.js / Node.js Modules

Working with Node.js Modules

In this tutorial, we will learn how to work with Node.js modules, both built-in and custom. We will explore how to import and use them in our applications.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores built-in, third-party, and custom modules in Node.js.

Working with Node.js Modules Tutorial

1. Introduction

Welcome to this tutorial on working with Node.js modules. Our goal is to help you understand how to import and use both built-in and custom Node.js modules in your applications.

You will learn how to:
- Import built-in Node.js modules
- Create and use custom Node.js modules
- Understand module scope and encapsulation

Prerequisites: Basic understanding of JavaScript and Node.js.

2. Step-by-Step Guide

Node.js has a simple module loading system where files and modules are in one-to-one correspondence. This means each file is treated as a separate module.

A module encapsulates related code into a single unit of code. This can be interpreted as moving all related functions into a file.

Importing Built-in Node.js Modules

Node.js comes with many built-in modules that you can use without any further installation. Here's how you can import a built-in module:

const fs = require('fs');

In the above line, fs is a built-in module that provides filesystem related functionalities.

Creating and Using Custom Node.js Modules

To create a custom Node.js module, you create a new file and use module.exports or exports to expose things you want to make public:

// myModule.js
module.exports = 'Hello world';

You can then use this module in another file:

// app.js
const myModule = require('./myModule');
console.log(myModule); // Outputs: Hello world

3. Code Examples

Example 1: Using the Path Module

// Importing the Path module
const path = require('path');

// Using the join method to concatenate paths
let completePath = path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');

console.log(completePath);
// Expected Output: '/foo/bar/baz/asdf'

// This example shows how to use the built-in Path module to handle file paths.

Example 2: Custom Module

// myModule.js
module.exports = function (num1, num2) {
    return num1 + num2;
}

// app.js
const addNum = require('./myModule');
console.log(addNum(5, 3)); // Outputs: 8

// This example shows how to create a custom module that exports a function, and then use it in another file.

4. Summary

In this tutorial, we've learned how to import and use built-in Node.js modules, create and use custom Node.js modules, and understand module scope and encapsulation.

Next, you can explore more about Node.js Event-Driven Architecture or learn about different Node.js frameworks like Express.js.

5. Practice Exercises

  1. Exercise 1: Create a custom module that exports an object with a method that returns the area of a circle given the radius.
  2. Exercise 2: Use the built-in http module to create a simple server that responds with a "Hello World" for every request.
  3. Exercise 3: Create a custom module that exports a function to write a JSON object to a file using the fs module.

  4. Hint: You can use the fs.writeFile method. Don't forget to stringify your JSON object before writing it to the file.

Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Favicon Generator

Create favicons from images.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help