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);
});
How to read and write files in Node JS ?
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.
Contact Us