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.');
});
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