Hey there, awesome devs! π Have you ever wondered how Node.js handles files, streams, networking, and more without installing extra packages? The secret lies in built-in modulesβpowerful tools that come preloaded with Node.js! π
π What Are Built-in Modules?
Built-in modules are core modules that come with Node.js, so you donβt need to install them separately. Just require or import them, and youβre good to go! π
Hereβs how to import built-in modules:
πΉ CommonJS (require)
const fs = require('fs');
πΉ ES Modules (import)
import fs from 'fs';
Now, letβs explore some of the most useful modules! π
π₯ 1. fs
(File System) - Work with Files π
The fs
module allows you to read, write, update, and delete files.
π Read a File
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
βοΈ Write to a File
fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log('File written successfully!');
});
π₯ 2. path
- Work with File Paths ποΈ
The path
module makes handling file paths easy and OS-independent.
π Get File Extension
const path = require('path');
console.log(path.extname('index.html')); // Output: .html
π Join Paths Correctly
console.log(path.join(__dirname, 'folder', 'file.txt'));
π₯ 3. http
- Create a Web Server π
The http
module lets you build simple web servers.
π Create a Basic Server
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
});
server.listen(3000, () => console.log('Server running on port 3000'));
Open http://localhost:3000/
in your browser and see it in action! π
π₯ 4. os
- Get System Information π₯οΈ
The os
module provides system-related info like OS type, memory, and CPU details.
π₯οΈ Get OS Type
const os = require('os');
console.log(os.type()); // Output: Windows_NT, Linux, Darwin
πΎ Check Free Memory
console.log(os.freemem());
π₯ 5. events
- Work with Events π―
The events
module allows you to create and handle custom events.
π₯ Create an Event Emitter
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
eventEmitter.on('greet', () => console.log('Hello, Developer!'));
eventEmitter.emit('greet');
π Final Thoughts
Node.js built-in modules make development faster and easier by providing powerful utilities right out of the box! Whether youβre handling files, paths, servers, or system info, Node.js has you covered! πͺ
Stay tuned for the next article, where weβll explore even more Callback Pattern! π―
If you found this blog helpful, make sure to follow me on GitHub π github.com/sovannaro and drop a β. Your support keeps me motivated to create more awesome content! π
Happy coding! π»π₯
Top comments (0)