Node.js Fundamentals

Learn Node.js from scratch including core concepts, modules, and basic server development.

beginner Backend Development 5 hours

Chapter 5: File System Operations

Chapter 5 of 15

Chapter 5: File System Operations

5.1 Reading Files

The fs module provides file system operations. Node.js offers both callback and promise-based APIs.

Callback-Based API:

const fs = require('fs');

// Read file asynchronously
fs.readFile('file.txt', 'utf8', (err, data) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }
    console.log(data);
});

// Read file synchronously (blocks execution)
try {
    const data = fs.readFileSync('file.txt', 'utf8');
    console.log(data);
} catch (err) {
    console.error('Error:', err);
}

Promise-Based API (fs/promises):

const fs = require('fs').promises;

// Using async/await
async function readFile() {
    try {
        const data = await fs.readFile('file.txt', 'utf8');
        console.log(data);
    } catch (err) {
        console.error('Error:', err);
    }
}

readFile();

Reading Options:

  • Encoding: 'utf8', 'ascii', 'base64'
  • Flag: 'r' (read), 'w' (write), 'a' (append)
  • Buffer: Read as binary data

5.2 Writing Files

Writing files allows you to save data to disk.

const fs = require('fs');

// Write file asynchronously
fs.writeFile('output.txt', 'Hello World', 'utf8', (err) => {
    if (err) {
        console.error('Error writing file:', err);
        return;
    }
    console.log('File saved');
});

// Append to file
fs.appendFile('log.txt', 'New log entry
', (err) => {
    if (err) throw err;
});

// Write synchronously
fs.writeFileSync('output.txt', 'Hello World', 'utf8');

Promise-Based Writing:

const fs = require('fs').promises;

async function writeFile() {
    try {
        await fs.writeFile('output.txt', 'Hello World', 'utf8');
        console.log('File written');
    } catch (err) {
        console.error('Error:', err);
    }
}

5.3 Directory Operations

Work with directories and file system structure.

const fs = require('fs');

// Create directory
fs.mkdir('new-folder', (err) => {
    if (err) throw err;
});

// Read directory contents
fs.readdir('.', (err, files) => {
    if (err) throw err;
    files.forEach(file => {
        console.log(file);
    });
});

// Check if path exists
fs.access('file.txt', fs.constants.F_OK, (err) => {
    if (err) {
        console.log('File does not exist');
    } else {
        console.log('File exists');
    }
});

// Get file stats
fs.stat('file.txt', (err, stats) => {
    if (err) throw err;
    console.log('Size:', stats.size);
    console.log('Is file:', stats.isFile());
    console.log('Is directory:', stats.isDirectory());
});

5.4 File System Best Practices

Follow best practices for file operations.

  • Use async methods to avoid blocking
  • Handle errors properly
  • Check file existence before operations
  • Use streams for large files
  • Validate file paths
  • Set appropriate file permissions