How to use the Node.js fs module for reading and writing files asynchronously



Image not found!!

In Node.js, the fs module provides file system-related functionality, including reading and writing files. To perform file operations asynchronously, you can use the asynchronous methods provided by the fs module. Here's a basic example of how to use the fs module for reading and writing files asynchronously:

Reading a File Asynchronously:

javascript
const fs = require('fs'); // Specify the file path const filePath = 'example.txt'; // Use readFile method to read the file asynchronously fs.readFile(filePath, 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } console.log('File content:', data); });

In this example, the readFile function is used to asynchronously read the contents of a file. The third parameter is a callback function that will be invoked once the file reading is complete. If there is an error during the reading process, it will be passed to the callback as the first argument (err).

Writing to a File Asynchronously:

javascript
const fs = require('fs'); // Specify the file path const filePath = 'example.txt'; // Data to be written to the file const contentToWrite = 'Hello, this is some content to be written to the file.'; // Use writeFile method to write to the file asynchronously fs.writeFile(filePath, contentToWrite, 'utf8', (err) => { if (err) { console.error('Error writing to file:', err); return; } console.log('File has been written successfully.'); });

In this example, the writeFile function is used to asynchronously write data to a file. The third parameter is the data to be written, and the fourth parameter is a callback function that will be invoked once the writing is complete. If there is an error during the writing process, it will be passed to the callback as the first argument (err).

Make sure to replace 'example.txt' with the actual path of the file you want to read or write. Additionally, handle errors appropriately based on your application's requirements.