π File Systems β Reading and Writing Files

Table of contents
- File Operations in Node.js: Simplified Reading and Writing Techniques
- I. π¦ The File System Module in Node.js
- 1. π§ Asynchronous File Operations
- 2.π§± Synchronous File Operations
- II. π₯ File Uploads Using Express and Multer
- III. π Understanding Callbacks & Streams
- π§ͺ Testing the App
- π¬ Letβs Connect!
- π¬ Telegram
- πΌ LinkedIn

File Operations in Node.js: Simplified Reading and Writing Techniques
Working with files in Node.js means being able to open, read, update, delete, or create new files β much like using a digital notebook. Node.js makes these operations easy through its built-in fs
(File System) module.
I. π¦ The File System Module in Node.js
Common File Operations
π Read files
π Create/write files
βοΈ Update file content
ποΈ Delete files
π Rename files
Importing the fs
Module
Depending on your module type in package.json
, use one of the following imports:-
- CommonJS
const fs = require('fs');
- ES Modules
const fs = require('fs');
π οΈ Project Setup
1 Initialize the project
npm init -y
2 Install the fs module
While
fs
is built-in and doesn't need installation, you might still install other packages. For clarity, you do not need to runnpm install fs
.3 Create a
src
folder and addindex.js
mkdir src touch src/index.js
Like this ππΌ
After npm install fs module view the packge.json file
βπΌ Two Ways to Handle File Systems in Node.js
Asynchronous (non-blocking): Executes operations without waiting.
Synchronous (blocking): Executes one operation at a time, in sequence.
1. π§ Asynchronous File Operations
Note: Use 'utf8'
encoding to handle readable text files properly.
β Callback Styles
1.// Normal Function
function (err, data) { ... }
2.// Arrow Function
(err, data) => { ... }
1. π Write File (Async)
import fs from 'fs';
fs.writeFile('example.txt', 'This is the fs file.', 'utf8', (err) => {
if (err) {
console.log('Failed to write file:', err);
} else {
console.log('File created successfully!');
}
});
Output:
2. π Read File (Async)
import fs from 'fs';
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.log('Failed to read file:', err);
} else {
console.log('File content:', data);
}
});
Output: Showing the file example.txt content
3. βοΈ Update File (Append)
import fs from 'fs';
fs.appendFile('example.txt', ' Appended content.', (err) => {
if (err) {
console.error('Error updating file:', err);
} else {
console.log('File updated successfully.');
}
});
4. π Rename File
import fs from 'fs';
fs.rename('oldname.txt', 'newname.txt', (err) => {
if (err) {
console.error('Error renaming file:', err);
} else {
console.log('File renamed successfully.');
}
});
5. ποΈ Delete File
import fs from 'fs';
fs.unlink('newfile.txt', (err) => {
if (err) {
console.error('Error deleting file:', err);
} else {
console.log('File deleted successfully.');
}
});
2.π§± Synchronous File Operations
1. π Write File (Sync)
import fs from 'fs'
try {
fs.writeFileSync('example.txt', 'This is the fs file.', 'utf8');
console.log('File created successfully!');
} catch (err) {
console.log('Failed to write file:', err);
}
2. π Read File (Sync)
import fs from 'fs'
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log('File content:', data);
} catch (err) {
console.log('Failed to read file:', err);
}
3. βοΈ Update File (Sync)
import fs from 'fs'
try {
fs.appendFileSync('example.txt', '\nAppended Content', 'utf8');
console.log('File updated successfully.');
} catch (err) {
console.error('Error updating file:', err);
}
4. π Rename File (Sync)
import fs from 'fs';
try {
fs.renameSync('example.txt', 'newname.txt');
console.log('File renamed successfully.');
} catch (err) {
console.error('Error renaming file:', err);
}
5. ποΈ Delete File (Sync)
import fs from 'fs';
try {
fs.unlinkSync('newname.txt');
console.log('File deleted successfully.');
} catch (err) {
console.error('Error deleting file:', err);
}
II. π₯ File Uploads Using Express and Multer
1.ποΈWhat is File Upload?
File upload is the process of sending a file from a client (e.g., browser) to a server for storage and later use.
The server needs to:
1. Receive the file.
2. Save it somewhere (usually on the computerβs hard drive).
3. Allow it to be accessed later (downloaded or viewed).
2.π 2. Setting Up File Upload with Express + Multer
π§Install dependencies:
npm install express multer
βοΈ Code:
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express(); const PORT = 3000;
// Set storage engine
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/'); // where to store
},
filename: function (req, file, cb)
{
const uniqueName = ${Date.now()}-${file.originalname};
cb(null, uniqueName);
},
});
// Initialize upload
const upload = multer({ storage: storage });
// Middleware to serve static files
app.use('/uploads', express.static('uploads'));
// Upload route
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) return res.status(400).send('No file uploaded.');
res.send({
message: 'File uploaded successfully!',
filePath: /uploads/${req.file.filename},
});
});
// Home route
app.get('/', (req, res) => {
res.send(`<form action="/upload" enctype="multipart/form-data" method="POST">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>`);
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Output:
After click the upload button save the selected file in the your selected folder.
III. π Understanding Callbacks & Streams
Callbacks
Used to handle results in asynchronous functions:
cb(null, 'uploads/');
This follows the Node.js callback pattern: callback(error, result)
.
Streams
Multer and fs
both use streams under the hood for efficiency.
Benefits
Efficient for large files
Processes data in chunks
Avoids loading the entire file into memory
πΌ Serving Uploaded Files
app.use('/uploads', express.static('uploads'));
Uploaded files can be accessed like:
http://localhost:3000/uploads/filename.png
π§ͺ Testing the App
- Start the server:
npm run start
- Visit:
http://localhost:3000
- Diagram of the upload process:
π Thanks for Reading!
Hope this guide helped you understand file handling in Node.js. If you found it useful, feel free to share or reach out with feedback. Happy coding! πππ»
π¬ Letβs Connect!
Have questions or want to connect professionally? Iβd love to hear from you!
Subscribe to my newsletter
Read articles from Pritam Suryawanshi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
