ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Node.js Tutorial• 7 min read

File System & Asynchronous I/O

Reading, writing, and manipulating disk files with fs/promises and path

The node:fs module provides access to the underlying filesystem. Using the promise-based API with async/await ensures clean, non-blocking file reads, writes, and directory operations.

Non-Blocking File Handling with fs/promises

Never use synchronous methods like readFileSync() inside web server request handlers because they block the entire single thread from serving other users.

Use node:path to construct cross-platform file paths (path.join(), path.resolve()), preventing Windows backslash vs Unix forward slash issues.

Handle missing files and permissions gracefully with try / catch blocks.

Reading and Writing JSON Files Asynchronously
import { readFile, writeFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import path from 'node:path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

async function updateConfig() {
  const filePath = path.join(__dirname, 'data', 'settings.json');
  
  try {
    // Read and parse configuration file
    const rawData = await readFile(filePath, 'utf-8');
    const settings = JSON.parse(rawData);
    
    // Mutate and save
    settings.lastUpdated = new Date().toISOString();
    settings.views = (settings.views || 0) + 1;
    
    await writeFile(filePath, JSON.stringify(settings, null, 2), 'utf-8');
    console.log('Configuration successfully saved to disk!');
  } catch (error) {
    console.error('File operation failed:', error.message);
  }
}

updateConfig();
path.join constructs valid paths across both Windows and Linux operating systems.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Why should you avoid methods like readFileSync() in production web servers?