0
0
NodejsHow-ToBeginner · 3 min read

How to Rename a File in Node.js Using fs.rename

In Node.js, you can rename a file using the fs.rename method from the built-in fs module. This method takes the current file path and the new file path as arguments and renames the file asynchronously.
📐

Syntax

The fs.rename method is used to rename or move a file. It requires three parameters:

  • oldPath: The current path of the file you want to rename.
  • newPath: The new path or name for the file.
  • callback: A function called after the operation completes, with an error argument if something goes wrong.
javascript
import { rename } from 'fs';

rename(oldPath, newPath, (err) => {
  if (err) throw err;
  console.log('File renamed successfully');
});
💻

Example

This example renames a file named oldfile.txt to newfile.txt. It shows how to handle errors and confirm success.

javascript
import { rename } from 'fs';

const oldPath = './oldfile.txt';
const newPath = './newfile.txt';

rename(oldPath, newPath, (err) => {
  if (err) {
    console.error('Error renaming file:', err.message);
    return;
  }
  console.log('File renamed successfully');
});
Output
File renamed successfully
⚠️

Common Pitfalls

Common mistakes when renaming files in Node.js include:

  • Not handling errors, which can cause your program to crash silently.
  • Using incorrect file paths or missing file extensions.
  • Trying to rename a file that does not exist.
  • Confusing synchronous and asynchronous methods.

Always check that the file exists and handle errors properly.

javascript
import { rename } from 'fs';

// Wrong: ignoring error
rename('missing.txt', 'newname.txt', () => {});

// Right: handle error
rename('missing.txt', 'newname.txt', (err) => {
  if (err) {
    console.error('Failed to rename:', err.message);
    return;
  }
  console.log('Renamed successfully');
});
📊

Quick Reference

Summary tips for renaming files in Node.js:

  • Use fs.rename for asynchronous renaming.
  • Always provide a callback to handle errors.
  • Paths can include directories to move files.
  • For synchronous renaming, use fs.renameSync but handle exceptions.

Key Takeaways

Use fs.rename(oldPath, newPath, callback) to rename files asynchronously in Node.js.
Always handle errors in the callback to avoid crashes or silent failures.
File paths must be correct and include extensions if needed.
You can move files by specifying a different directory in newPath.
For synchronous operations, use fs.renameSync but catch exceptions.