Read and Write Files using fs Module
Question
Write a Node.js program to create a file, write data into it, and then read the file content using the fs module.
Coding Answer
const fs = require("fs");
// Write to file
fs.writeFile("example.txt", "Hello Node.js", (err) => {
if (err) throw err;
console.log("File written successfully");
// Read file
fs.readFile("example.txt", "utf8", (err, data) => {
if (err) throw err;
console.log("File content:", data);
});
});Preview
Run the file using Node.js:
node app.js
👉 Output in terminal:
File written successfully File content: Hello Node.js
Explanation
- fs module is used to work with the file system
- writeFile() creates and writes data to a file
- readFile() reads data from the file
- Callbacks handle asynchronous operations
- "utf8" ensures readable text output