0
0
NodejsHow-ToBeginner · 3 min read

How to Use fs.rename in Node.js: Simple File Rename Guide

Use fs.rename(oldPath, newPath, callback) in Node.js to rename or move a file asynchronously. Provide the current file path as oldPath, the new file path as newPath, and a callback to handle success or errors.
📐

Syntax

The fs.rename function takes three arguments:

  • oldPath: The current path of the file you want to rename or move.
  • newPath: The new path or name for the file.
  • callback: A function called after the operation finishes, with an error argument if something went wrong.

This function works asynchronously and does not block your program.

javascript
fs.rename(oldPath, newPath, (err) => {
  if (err) throw err;
  console.log('Rename successful!');
});
💻

Example

This example renames a file named example.txt to renamed.txt in the same folder. It logs a success message or an error if the file does not exist.

javascript
import { rename } from 'fs';

rename('example.txt', 'renamed.txt', (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 using fs.rename include:

  • Trying to rename a file that does not exist, which causes an error.
  • Not handling the error in the callback, which can crash your program.
  • Using fs.rename to move files across different drives or partitions, which may fail on some systems.

Always check for errors in the callback and ensure the source file exists before renaming.

javascript
import { rename } from 'fs';

// Wrong: no error handling
rename('missing.txt', 'newname.txt', () => {
  console.log('Done');
});

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

Quick Reference

Summary tips for using fs.rename:

  • Use absolute or relative paths for oldPath and newPath.
  • Always provide a callback to handle errors.
  • It works asynchronously, so your program continues running while renaming.
  • For synchronous renaming, use fs.renameSync instead.
  • To move files across drives, consider copying and deleting instead.

Key Takeaways

Use fs.rename(oldPath, newPath, callback) to rename or move files asynchronously in Node.js.
Always handle errors in the callback to avoid crashes and detect issues.
fs.rename can move files within the same drive but may fail across drives or partitions.
For synchronous operations, use fs.renameSync, but prefer async for non-blocking code.
Check that the source file exists before renaming to prevent errors.