πŸ“ File Systems – Reading and Writing Files

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 run npm install fs.

  • 3 Create a src folder and add index.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

  1. Start the server:
npm run start
  1. Visit:
http://localhost:3000
  1. 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!

0
Subscribe to my newsletter

Read articles from Pritam Suryawanshi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pritam Suryawanshi
Pritam Suryawanshi