Working with Node.js Modules

Tutorial 2 of 5

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!