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. 💡
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. 💡
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:
// 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. ✅
Node.js provides several core modules that are pre-installed. Let's take a look at two essential core modules:
fs - File System: This module allows you to read, write, and delete files.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.
http - HTTP: This module allows you to create HTTP servers and handle requests.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.
You can also create your custom modules and share them with others. Let's create a simple custom module for math operations:
// 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:
// main.js
const math = require('./math');
console.log(math.add(2, 3)); // Output: 5
console.log(math.subtract(5, 3)); // Output: 2Which 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! 💡