WikiGalaxy

Personalize

Working with File System in Node.js (fs)

Introduction to fs Module

Node.js provides a built-in module called fs (File System) that allows developers to work with the file system on their machine. This module provides both synchronous and asynchronous methods to read, write, update, delete, and rename files. Understanding how to use the fs module is crucial for backend development tasks such as logging, data storage, and file manipulation.

Reading Files

Asynchronous File Reading

The fs.readFile() method is used to read files asynchronously. It doesn't block the execution of the program, making it ideal for non-blocking operations.


const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log(data);
});
        

Synchronous File Reading

The fs.readFileSync() method reads files synchronously, blocking the execution until the file is read. It's useful when you need to ensure that the file is read before proceeding.


const fs = require('fs');
try {
    const data = fs.readFileSync('example.txt', 'utf8');
    console.log(data);
} catch (err) {
    console.error(err);
}
        

Writing Files

Asynchronous File Writing

The fs.writeFile() method allows you to write data to a file asynchronously. It creates a new file if it doesn't exist, or overwrites the file if it does.


const fs = require('fs');
fs.writeFile('example.txt', 'Hello, World!', (err) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log('File written successfully');
});
        

Synchronous File Writing

The fs.writeFileSync() method writes data to a file synchronously. It's useful when you need to ensure that the data is written before proceeding.


const fs = require('fs');
try {
    fs.writeFileSync('example.txt', 'Hello, Synchronous World!');
    console.log('File written successfully');
} catch (err) {
    console.error(err);
}
        

Updating Files

Appending to Files

The fs.appendFile() method is used to append data to a file asynchronously. If the file doesn't exist, it creates a new one.


const fs = require('fs');
fs.appendFile('example.txt', '\nAppended Text', (err) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log('Text appended successfully');
});
        

Truncating Files

The fs.truncate() method is used to truncate a file to a specified length. This can be useful for clearing or resizing a file.


const fs = require('fs');
fs.truncate('example.txt', 10, (err) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log('File truncated successfully');
});
        

Deleting Files

Removing Files

The fs.unlink() method is used to delete a file asynchronously. This is useful for cleaning up files that are no longer needed.


const fs = require('fs');
fs.unlink('example.txt', (err) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log('File deleted successfully');
});
        

Synchronous File Deletion

The fs.unlinkSync() method deletes a file synchronously. This is useful when you need to ensure that the file is deleted before proceeding.


const fs = require('fs');
try {
    fs.unlinkSync('example.txt');
    console.log('File deleted successfully');
} catch (err) {
    console.error(err);
}
        

Renaming Files

Renaming Files Asynchronously

The fs.rename() method is used to rename a file asynchronously. This can also be used to move a file across directories.


const fs = require('fs');
fs.rename('oldname.txt', 'newname.txt', (err) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log('File renamed successfully');
});
        

Synchronous File Renaming

The fs.renameSync() method renames a file synchronously. It's useful when you need to ensure that the file is renamed before proceeding.


const fs = require('fs');
try {
    fs.renameSync('oldname.txt', 'newname.txt');
    console.log('File renamed successfully');
} catch (err) {
    console.error(err);
}
        

Watching Files

Monitoring File Changes

The fs.watch() method allows you to monitor changes to a file or directory. It's useful for implementing features like auto-reloading or real-time updates.


const fs = require('fs');
fs.watch('example.txt', (eventType, filename) => {
    console.log(`File ${filename} has been ${eventType}`);
});
        

File Permissions and Ownership

Changing File Permissions

The fs.chmod() method is used to change the permissions of a file. This is important for securing files and controlling access.


const fs = require('fs');
fs.chmod('example.txt', 0o775, (err) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log('File permissions changed successfully');
});
        

Error Handling in fs Operations

Handling Errors Gracefully

File operations can often result in errors, such as when a file doesn't exist or there's a permission issue. Proper error handling is crucial to ensure your application runs smoothly and provides informative feedback.


const fs = require('fs');
fs.readFile('nonexistent.txt', 'utf8', (err, data) => {
    if (err) {
        console.error('An error occurred:', err.message);
        return;
    }
    console.log(data);
});
        
logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025