NodeJS Filesystem Module


What is the File System (fs) module in Node.js?

The File System (fs) module in Node.js provides an API for interacting with the file system. It allows you to read, write, delete, rename, and perform other operations on files and directories. The fs module supports both synchronous and asynchronous methods for handling file operations, where asynchronous methods are non-blocking and use callbacks.


How do you read a file in Node.js using the fs module?

The fs module provides both asynchronous and synchronous methods to read files in Node.js:

Asynchronous example using fs.readFile():

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
    if (err) {
        console.error('Error reading file:', err);
    } else {
        console.log('File content:', data);
    }
});

Synchronous example using fs.readFileSync():

const fs = require('fs');

const data = fs.readFileSync('example.txt', 'utf8');
console.log('File content:', data);

How do you write to a file in Node.js using the fs module?

To write data to a file in Node.js, you can use the asynchronous fs.writeFile() or the synchronous fs.writeFileSync() methods. These methods either create a new file or overwrite an existing file.

Asynchronous example using fs.writeFile():

const fs = require('fs');

fs.writeFile('example.txt', 'Hello, Node.js!', 'utf8', (err) => {
    if (err) {
        console.error('Error writing to file:', err);
    } else {
        console.log('File written successfully');
    }
});

Synchronous example using fs.writeFileSync():

const fs = require('fs');

fs.writeFileSync('example.txt', 'Hello, Node.js!', 'utf8');
console.log('File written successfully');

How do you append data to an existing file in Node.js?

To append data to an existing file in Node.js, you can use the asynchronous fs.appendFile() or synchronous fs.appendFileSync() methods. These methods add data to the end of the file without overwriting it.

Asynchronous example using fs.appendFile():

const fs = require('fs');

fs.appendFile('example.txt', '
Appended data', 'utf8', (err) => {
    if (err) {
        console.error('Error appending to file:', err);
    } else {
        console.log('Data appended successfully');
    }
});

Synchronous example using fs.appendFileSync():

const fs = require('fs');

fs.appendFileSync('example.txt', '
Appended data', 'utf8');
console.log('Data appended successfully');

How do you delete a file in Node.js?

To delete a file in Node.js, you can use the asynchronous fs.unlink() method or the synchronous fs.unlinkSync() method.

Asynchronous example using fs.unlink():

const fs = require('fs');

fs.unlink('example.txt', (err) => {
    if (err) {
        console.error('Error deleting file:', err);
    } else {
        console.log('File deleted successfully');
    }
});

Synchronous example using fs.unlinkSync():

const fs = require('fs');

fs.unlinkSync('example.txt');
console.log('File deleted successfully');

How do you check if a file or directory exists in Node.js?

To check if a file or directory exists, you can use the fs.existsSync() method. It returns true if the file or directory exists and false otherwise.

const fs = require('fs');

if (fs.existsSync('example.txt')) {
    console.log('File exists');
} else {
    console.log('File does not exist');
}

How do you create a directory in Node.js?

You can create a directory using the fs.mkdir() method for asynchronous creation or fs.mkdirSync() for synchronous creation.

Asynchronous example using fs.mkdir():

const fs = require('fs');

fs.mkdir('new_directory', (err) => {
    if (err) {
        console.error('Error creating directory:', err);
    } else {
        console.log('Directory created successfully');
    }
});

Synchronous example using fs.mkdirSync():

const fs = require('fs');

fs.mkdirSync('new_directory');
console.log('Directory created successfully');

How do you read the contents of a directory in Node.js?

To read the contents of a directory in Node.js, you can use the fs.readdir() method for asynchronous reading or fs.readdirSync() for synchronous reading. These methods return an array of filenames contained in the directory.

Asynchronous example using fs.readdir():

const fs = require('fs');

fs.readdir('my_directory', (err, files) => {
    if (err) {
        console.error('Error reading directory:', err);
    } else {
        console.log('Directory contents:', files);
    }
});

Synchronous example using fs.readdirSync():

const fs = require('fs');

const files = fs.readdirSync('my_directory');
console.log('Directory contents:', files);

How do you rename a file or directory in Node.js?

To rename a file or directory in Node.js, you can use the fs.rename() method for asynchronous renaming or fs.renameSync() for synchronous renaming.

Asynchronous example using fs.rename():

const fs = require('fs');

fs.rename('old_name.txt', 'new_name.txt', (err) => {
    if (err) {
        console.error('Error renaming file:', err);
    } else {
        console.log('File renamed successfully');
    }
});

Synchronous example using fs.renameSync():

const fs = require('fs');

fs.renameSync('old_name.txt', 'new_name.txt');
console.log('File renamed successfully');
Ads