mdawar.dev

A blog about programming, Web development, Open Source, Linux and DevOps.

Move File in Node.js

Move a file in Node.js and handle non-existent directories and different mount points.

js
import path from 'node:path';
import fs from 'node:fs/promises';

export async function moveFile(oldPath, newPath) {
  // Create the destination directory if it doesn't exist
  await fs.mkdir(path.dirname(newPath), { recursive: true });

  try {
    // Rename the file (move it to the new directory)
    await fs.rename(oldPath, newPath);
  } catch (error) {
    // Handle different mount points
    if (error.code === 'EXDEV') {
      // Copy the file as a fallback
      await fs.copyFile(oldPath, newPath);
      // Remove the old file
      await fs.unlink(oldPath);
    } else {
      throw error;
    }
  }
}

Read more: How to Move a File in Node.js?