Core Modules (fs & path)
Working with the File System and Path modules natively.
🧑🏫 Sabse pehle — simple mein samjho#
Node.js apne andar pehle se hi kuch bahot powerful features (Core Modules) leke aata hai, jinke liye tumhe koi extra NPM package install karne ki zaroorat nahi padti. Agar tumhe computer ki hard drive se file read karni hai, ya nayi file banani hai, toh fs (File System) module use hota hai. Agar tumhe file ke raston (paths) ke sath khelna hai taaki code Mac aur Windows dono pe properly chale, toh path module use hota hai.
1. The path Module#
Mac/Linux use forward slashes for paths (/users/folder), while Windows uses backslashes (\users\folder). The path module handles these differences automatically so your code runs flawlessly on any operating system.
const path = require('path');
// 1. path.join() - Safely joins pieces into a full path
const folderPath = path.join('/users', 'tarun', 'docs', 'file.txt');
console.log(folderPath); // Mac: /users/tarun/docs/file.txt
// 2. path.resolve() - Always returns an absolute path from the root directory
const absolutePath = path.resolve('docs', 'file.txt');
// 3. Extracting info from a path
const filePath = '/users/tarun/image.png';
console.log(path.basename(filePath)); // "image.png"
console.log(path.extname(filePath)); // ".png"
console.log(path.dirname(filePath)); // "/users/tarun"
2. The fs (File System) Module#
The fs module allows you to interact with the hard drive. Historically it used callbacks, but modern Node.js heavily promotes the Promise-based version (fs/promises), which allows us to use async/await.
Using fs/promises (The Modern Way)#
const fs = require('fs/promises');
// If using ESM: import fs from 'fs/promises';
async function handleFiles() {
try {
// 1. Write to a file (Overwrites if it exists)
await fs.writeFile('message.txt', 'Hello World!');
// 2. Append to a file (Adds to the end)
await fs.appendFile('message.txt', '\nThis is a new line.');
// 3. Read a file
// Note: You must specify 'utf-8' encoding, otherwise it returns a raw Buffer (binary data)
const data = await fs.readFile('message.txt', 'utf-8');
console.log(data);
// 4. Delete a file
// await fs.unlink('message.txt');
} catch (error) {
console.error("File system error:", error);
}
}
handleFiles();
Why not fs.readFileSync?#
You will see fs.readFileSync and fs.writeFileSync in many older tutorials. As discussed in the Event Loop notes, synchronous methods block the entire Node.js thread. They should only be used during the initial startup phase of your application (like reading a config file before the server starts accepting requests). Never use them inside a route handler!