// Import 'fs' module
const fs = require('fs');
// Read a file
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Write to a file
fs.writeFile('newfile.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log('File written successfully.');
});
code
Read and Write Files in Node.js using 'fs' module
This Node.js code demonstrates reading content from a file ('file.txt') and writing to a new file ('newfile.txt') using the 'fs' module. The comments provide explanations for each part of the code.
File Reading
Node.js
fs module
File Writing