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

Copying and Moving Files with fs.copyFile() and fs.rename()

Duplicating files and renaming or moving them to different locations.

Copying and Moving Files with fs.copyFile() and fs.rename()

You'll learn how to duplicate files and relocate or rename them using Node.js's file system methods.

Core Concept

When working with files, you often need to create duplicates or reorganize them. Node.js provides two dedicated methods:

  • fs.copyFile() duplicates a file, leaving the original intact
  • fs.rename() moves or renames a file, removing it from its original location

Think of copyFile() like photocopying a document—you end up with two copies. Meanwhile, rename() is like picking up a physical file folder and moving it to a different drawer, or simply relabeling it.

Copying Files

import { copyFile } from 'fs/promises';

// Duplicate a file
await copyFile('source.txt', 'copy.txt');

This creates an exact duplicate. If copy.txt already exists, it will be overwritten by default.

Renaming and Moving Files

import { rename } from 'fs/promises';

// Rename a file
await rename('old-name.txt', 'new-name.txt');

// Move to a different directory
await rename('file.txt', 'archive/file.txt');

// Move AND rename simultaneously
await rename('temp.txt', 'final/document.txt');

Despite its name, rename() handles both renaming and moving. It's a single operation: specify a new path, and the file moves there. If you change the directory portion of the path, it moves; if you change the filename portion, it renames; change both, and it does both at once.

Important Notes

Both methods are asynchronous (when using the promises API), so use await or handle them as promises. The original file location becomes invalid after rename() succeeds—there's no copy left behind.

Key Takeaway: Use fs.copyFile() to duplicate files keeping the original, and fs.rename() to move or rename files in a single operation.