NodeJS Modules
I have joined and started learning Software development with ChaiCode Web dev Cohort 2026 and very excited😊
Lets learn about path module of nodejs
path module helps to get files and directory and works with it and write code for cross platform code . like getting files from any operating system like macos, linux and windows . so the code can access files system .
some methods and working with path module
like in unix based system , the path may looks like 'users/mackin/file.txt' and in windows it look different like 'C:\users\joe\file.txt'
Some Methods in Path Module
dirname : to get directory of file
basename : to extract file name
extname: to get extension of ifle
// importing path module
import path from 'node:path';
const notes = '/users/dipesh/documents/notes.txt';
//! getting filename from path
console.log(path.basename(notes));
//! getting dirname
console.log(path.dirname(notes));
//! getting extension name
console.log(path.extname(notes));
// output
notes.txt
/users/dipesh/documents
.txt
Working with paths
// importing path module
import path from 'node:path';
const notes = '/users/dipesh/documents/notes.txt';
//! getting filename from path
// console.log(path.basename(notes));
//! getting dirname
// console.log(path.dirname(notes));
//! getting extension name
// console.log(path.extname(notes));
//! joining paths
const username = 'dipesh';
console.log(path.join('/', 'users', username, 'notes.txt'));
//! resolving paths, getting absolute path
console.log(path.resolve('notes.txt'));
// path.resolve('joe.txt'); // '/Users/joe/joe.txt' if run from my home folder
console.log(path.resolve('src', 'users.txt'));
// first parameters takes as base for second
console.log(path.resolve('/etc', 'notes.js'));
//if first parameters start with slash then it taken as absolute path
console.log(import.meta.dirname);
console.log(import.meta.filename);
console.log(
path.basename(import.meta.filename, path.extname(import.meta.filename)),
);
FS Module
fs module helps to create file, read, write, delete, rename, append files.
// create
// append
// rename
// delete
const fs = require('node:fs');
const path = require('node:path');
const folderPath = path.join(__dirname, 'studentsFolder');
const filePath = path.join(folderPath, 'students.pdf');
console.log(folderPath);
//!1. create folder
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath);
console.log('folder created');
}
// !2. create file
fs.writeFileSync(filePath, 'This is students file');
// console.log('file created');
fs.appendFileSync(filePath, '\nThis is appended text');
console.log('file updated');
//!4. read file
// const content = fs.readFileSync(filePath, 'utf-8');
// console.log('file content :', content);
//!5.delete file
// fs.unlinkSync(filePath);
// console.log('file deleted');

