How do you read and write files in Node.js?

Beginner

Answer

Node.js provides both synchronous and asynchronous methods for file operations:

const fs = require('fs');

// Asynchronous (recommended)
fs.readFile('input.txt', 'utf8', (err, data) => {
    if (err) throw err;
    console.log('File content:', data);
});

fs.writeFile('output.txt', 'Hello World', (err) => {
    if (err) throw err;
    console.log('File written successfully');
});

// Synchronous (blocking)
try {
    const data = fs.readFileSync('input.txt', 'utf8');
    fs.writeFileSync('output.txt', data.toUpperCase());
} catch (err) {
    console.error('Error:', err);
}

// Promise-based
const fsPromises = require('fs').promises;
const data = await fsPromises.readFile('input.txt', 'utf8');