fs is Node.js's built-in module for working with the file system. It's commonly used for backend tasks like reading files, writing files, checking folders, saving log files, and reading JSON data.
const fs = require('fs');
const note = 'Node.js can write files!';
// Write a file
fs.writeFile('note.txt', note, 'utf8', (writeErr) => {
if (writeErr) {
console.error('Write error:', writeErr.message);
return;
}
// Read the file after writing
fs.readFile('note.txt', 'utf8', (readErr, data) => {
if (readErr) {
console.error('Read error:', readErr.message);
return;
}
console.log('File content:', data);
});
});First, we write a note.txt file. After writing, we read it back inside the callback using fs.readFile(). If there's an error, we return early and show the error message.
File content: Node.js can write files!Info
An incorrect file path can cause read/write errors. In production apps, you should never do file operations without error handling.