Skip to main content

Archive

Show more

Node.js File System Operations

Node.js File System Operations

Node.js provides a built-in module called the File System module (fs) that allows you to perform various file system operations such as reading from and writing to files, creating and deleting files and directories, and more. These file system operations enable you to interact with the file system on your machine directly from your Node.js application.


1. Reading from a File

You can read data from a file using the fs.readFile() method. This method asynchronously reads the entire contents of a file.

Example:

const fs = require('fs');

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

This code reads the contents of the file example.txt using UTF-8 encoding and logs the data to the console.


2. Writing to a File

You can write data to a file using the fs.writeFile() method. This method asynchronously writes data to a file, overwriting the file if it already exists.

Example:

const fs = require('fs');

const content = 'This is the content that will be written to the file.';

fs.writeFile('example.txt', content, (err) => {
    if (err) {
        console.error('Error writing to file:', err);
        return;
    }
    console.log('File has been written successfully.');
});

This code writes the content to the file example.txt and logs a success message to the console.


3. Working with Directories

Node.js allows you to perform various operations on directories, such as creating, reading, and deleting directories.

Example of creating a directory:

const fs = require('fs');

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

This code creates a directory named my-directory.


4. Conclusion

Node.js provides a powerful File System module that allows you to perform various file system operations directly from your JavaScript code. Whether you need to read from or write to files, create or delete directories, or perform other file system tasks, Node.js has you covered with its comprehensive set of file system APIs.

Comments