SyntaxStudy
Sign Up
Node.js Reading and Writing Files
Node.js Beginner 10 min read

Reading and Writing Files

The fs (file system) module provides APIs to interact with the file system. Use the fs/promises API with async/await for clean, non-blocking code.

Common operations: reading files, writing files, appending, and checking if a file exists.

Example
const fs = require('fs/promises');
const path = require('path');

async function fileDemo() {
    const filePath = path.join(__dirname, 'data.txt');

    // Write a file (creates or overwrites):
    await fs.writeFile(filePath, 'Hello, Node.js!\nLine 2\n', 'utf8');
    console.log('File written.');

    // Read a file:
    const content = await fs.readFile(filePath, 'utf8');
    console.log('Content:', content);

    // Append to a file:
    await fs.appendFile(filePath, 'Line 3 appended.\n', 'utf8');

    // Get file stats:
    const stats = await fs.stat(filePath);
    console.log('Size:', stats.size, 'bytes');
    console.log('Modified:', stats.mtime);

    // Check existence (try/catch is the modern way):
    try {
        await fs.access(filePath);
        console.log('File exists');
    } catch {
        console.log('File does not exist');
    }

    // Delete the file:
    await fs.unlink(filePath);
    console.log('File deleted.');
}

fileDemo().catch(console.error);