Course contentsShow
← JavaScript
Lesson 1530 of 2,72333. JavaScript in Node.jsFree lesson

Error Handling Patterns in FS Operations

Dealing with ENOENT, EACCES, and other filesystem errors gracefully.

Error Handling Patterns in FS Operations

You'll learn how to gracefully handle common filesystem errors like ENOENT and EACCES when working with Node.js files.

When performing filesystem operations, things will go wrong—files won't exist, permissions will be denied, or disks will be full. The key is catching these errors gracefully rather than crashing your application.

Understanding Common FS Errors

ENOENT (Error NO ENTry) means "file or directory not found"—the path you specified doesn't exist.

EACCES (Error ACCESs) means you lack permission to read, write, or execute the file.

EEXIST means a file or directory already exists when you tried to create it.

Think of these like traffic signals: red (EACCES - can't proceed), missing road (ENOENT - path doesn't exist), or roadblock (EEXIST - already there).

Handling Errors Properly

With callbacks, check the err parameter first:

fs.readFile('config.json', 'utf8', (err, data) => {
  if (err) {
    if (err.code === 'ENOENT') {
      console.log('Config file not found, using defaults');
      // Use default configuration
      return;
    }
    if (err.code === 'EACCES') {
      console.error('Permission denied to read config');
      process.exit(1);
    }
    throw err; // Unexpected error
  }
  // Process data
});

With promises, use try-catch:

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

try {
  await fs.mkdir('logs');
} catch (err) {
  if (err.code === 'EEXIST') {
    console.log('Logs directory already exists');
  } else {
    throw err;
  }
}

Pattern: Fail Gracefully

Always check err.code to distinguish between recoverable issues (missing optional file) and critical failures (permission denied on required resource).

Key Takeaway: Check the err.code property (like ENOENT, EACCES) to handle specific filesystem errors appropriately rather than treating all errors the same way.