This content originally appeared on DEV Community and was authored by Kumar Ayush
Whether you’re just diving into backend development or brushing up on Node.js fundamentals, understanding the built-in fs and path modules is a game changer. These core modulesβavailable without any external installationβlay the groundwork for working efficiently with files and directories across platforms.
Why Core Modules Matter
Node.js ships with powerful internal tools like fs (file system) and path (path utilities) to help developers:
Read, write, and manage files with ease
Build platform-agnostic paths that work seamlessly across Windows, Linux, and macOS
Letβs explore how these tools fit into your developer toolkit.
Working with the fs Module
The fs module allows both synchronous and asynchronous file operationsβideal for learning and production use respectively.
** Writing Files
**js
// Synchronous
fs.writeFileSync('example.txt', 'Hello, Node.js!');
// Asynchronous
fs.writeFile('exampleAsync.txt', 'Async Hello!', (err) => {
if (err) throw err;
console.log('File created!');
});
Reading Files
js
// Synchronous
const data = fs.readFileSync('example.txt', 'utf-8');
console.log(data);
// Asynchronous
fs.readFile('exampleAsync.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log(data);
});
Appending Content
js
fs.appendFileSync('example.txt', '\nThis is a new line.');
fs.appendFile('example.txt', '\nAsync line here.', (err) => {
if (err) throw err;
});
Deleting Files
js
fs.unlinkSync('example.txt');
fs.unlink('exampleAsync.txt', (err) => {
if (err) throw err;
console.log('File deleted!');
});
Directories and Listing Contents
js
// Create folder
fs.mkdirSync('myFolder');
// Read current directory
const files = fs.readdirSync('.');
console.log(files);
Navigating with the path Module
The path module keeps your file paths robust and cross-platform.
Common Utilities
js
const path = require('path');
// Joins segments into a normalized path
const filePath = path.join('folder', 'file.txt');
// Gets full absolute path
const absolutePath = path.resolve('folder', 'file.txt');
// Extracts file name, dir, and extension
const base = path.basename('/users/kumar/index.js');
const dir = path.dirname('/users/kumar/index.js');
const ext = path.extname('index.js');
Utility Checks
js
path.isAbsolute('/folder/file.txt'); // true
path.normalize('folder/../folder2/./file.txt'); // 'folder2/file.txt'
In Tandem: fs + path
js
const fullPath = path.join(__dirname, ‘notes’, ‘todo.txt’);
fs.writeFileSync(fullPath, ‘Complete MERN Day 2’);
Wrap-Up
The fs and path modules offer an elegant way to work with files in a platform-safe, efficient manner. Mastering them early on sets the foundation for scalable file operations in real-world applications.
Stay tuned as I continue my MERN stack journeyβnext up, diving into server-side routing and handling requests using Express.js!!
This content originally appeared on DEV Community and was authored by Kumar Ayush