Open In App

How to read and write files in Node JS ?

Last Updated : 06 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

NodeJS provides built-in modules for reading and writing files, allowing developers to interact with the file system asynchronously. These modules, namely fs (File System), offer various methods for performing file operations such as reading from files, writing to files, and manipulating file metadata. Let’s explore how to read and write files in NodeJS.

Reading Files:

To read from a file in NodeJS, you can use the fs.readFile() method. This method asynchronously reads the entire contents of a file and passes the data to a callback function.

const fs = require('fs');

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

Writing Files:

To write to a file in NodeJS, you can use the fs.writeFile() method. This method asynchronously writes data to a file, replacing the file if it already exists or creating a new file if it doesn’t exist.

const fs = require('fs');

const content = 'This is the content to be written to the file.';
fs.writeFile('example.txt', content, 'utf8', (error) => {
if (error) {
console.error('An error occurred while writing to the file:', error);
return;
}
console.log('File has been written successfully.');
});

Synchronous File Operations:

NodeJS also provides synchronous versions of file operations, such as fs.readFileSync() and fs.writeFileSync(), which block the execution thread until the operation completes. While synchronous operations may be suitable for certain use cases, they can potentially block the event loop and impact the overall performance of the application, especially in I/O-bound scenarios.

Handling File Paths:

When working with file paths in NodeJS, it’s essential to handle path resolution and normalization correctly, especially when dealing with relative paths. NodeJS provides the path module to help manipulate file paths cross-platform.

const path = require('path');
const absolutePath = path.resolve(__dirname, 'example.txt');

Conclusion:

NodeJS offers powerful modules for reading and writing files asynchronously, enabling developers to interact with the file system seamlessly. By using methods provided by the fs module, handling file operations asynchronously, and properly managing file paths, developers can build robust and efficient file processing applications in NodeJS.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads