Node.js Built-in Modules Tutorial 🎯

beginner
8 min

Node.js Built-in Modules Tutorial 🎯

Welcome to our in-depth guide on Node.js Built-in Modules! This tutorial is designed to help both beginners and intermediates understand the power of Node.js's built-in modules, with practical examples that are relevant to real-world projects. 💡

What are Node.js Built-in Modules? 📝

Built-in modules are pre-installed libraries in Node.js that provide various functionalities without the need for additional installation. They simplify our development process by providing standard functionalities such as file system operations, HTTP requests, and more. 💡

Understanding the Module System 📝

Node.js follows a CommonJS module system. Each file is a separate module, and you can import other modules using the require() function. Let's dive into our first example:

javascript
// main.js const hello = require('./hello'); console.log(hello.helloWorld()); // hello.js module.exports = { helloWorld: function () { return 'Hello, World!'; } };

In this example, we have two files - main.js and hello.js. We require the hello module from hello.js in main.js and call the helloWorld function. ✅

Core Modules 📝

Node.js provides several core modules that are pre-installed. Let's take a look at two essential core modules:

  1. fs - File System: This module allows you to read, write, and delete files.
javascript
const fs = require('fs'); fs.readFile('file.txt', 'utf8', function (err, data) { if (err) throw err; console.log(data); });

In this example, we read the content of file.txt using the fs module.

  1. http - HTTP: This module allows you to create HTTP servers and handle requests.
javascript
const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!\n'); }); server.listen(3000, 'localhost', () => { console.log('Server running at http://localhost:3000/'); });

In this example, we create an HTTP server using the http module and respond with 'Hello, World!' to requests.

Creating Custom Modules 📝

You can also create your custom modules and share them with others. Let's create a simple custom module for math operations:

javascript
// math.js module.exports = { add: function (a, b) { return a + b; }, subtract: function (a, b) { return a - b; } };

Now, you can use this module in other files like so:

javascript
// main.js const math = require('./math'); console.log(math.add(2, 3)); // Output: 5 console.log(math.subtract(5, 3)); // Output: 2

Quiz 📝

Quick Quiz
Question 1 of 1

Which function is used to import modules in Node.js?

That's it for this lesson! You now have a good understanding of Node.js built-in modules and how to create custom modules. Happy coding! 💡