0
0
Node.jsframework~5 mins

Checking file existence and stats in Node.js

Choose your learning style9 modes available
Introduction

We check if a file exists and get its details to decide what to do next, like reading or writing it safely.

Before reading a file to avoid errors if it is missing.
To get file size or modification date for display or processing.
To check if a path is a file or a folder before handling it.
Before deleting a file to confirm it is there.
To verify permissions or ownership of a file.
Syntax
Node.js
import { promises as fs } from 'fs';

// Check if file exists
try {
  await fs.access('path/to/file');
  // File exists
} catch {
  // File does not exist
}

// Get file stats
const stats = await fs.stat('path/to/file');

Use fs.access to check if a file can be accessed (exists and permissions).

Use fs.stat to get detailed info like size, creation date, and type.

Examples
This checks if 'example.txt' exists and prints a message.
Node.js
import { promises as fs } from 'fs';

async function checkFile() {
  try {
    await fs.access('example.txt');
    console.log('File exists');
  } catch {
    console.log('File does not exist');
  }
}

checkFile();
This gets and prints size, type, and creation time of 'example.txt'.
Node.js
import { promises as fs } from 'fs';

async function showStats() {
  const stats = await fs.stat('example.txt');
  console.log(`Size: ${stats.size} bytes`);
  console.log(`Is file: ${stats.isFile()}`);
  console.log(`Created: ${stats.birthtime}`);
}

showStats();
Sample Program

This program checks if 'test.txt' exists. If yes, it prints its size, confirms it is a file, and shows last modified time. If not, it says the file does not exist.

Node.js
import { promises as fs } from 'fs';

async function checkAndShow() {
  const path = 'test.txt';
  try {
    await fs.access(path);
    const stats = await fs.stat(path);
    console.log(`File '${path}' exists.`);
    console.log(`Size: ${stats.size} bytes`);
    console.log(`Is file: ${stats.isFile()}`);
    console.log(`Last modified: ${stats.mtime}`);
  } catch {
    console.log(`File '${path}' does not exist.`);
  }
}

checkAndShow();
OutputSuccess
Important Notes

Always use try/catch with fs.access because it throws if file is missing.

fs.stat returns an object with many useful methods like isFile() and isDirectory().

Use await to handle these async calls cleanly.

Summary

Use fs.access to check if a file exists safely.

Use fs.stat to get file details like size and type.

Handle errors with try/catch to avoid crashes.