Rename a File in Node.js with fs.rename()

In Node.js, you can rename a file by using the fs.rename() method for an asynchronous rename operation or fs.renameSync() for a blocking synchronous rename operation. Both methods are part of the built-in Node FS module, so you do not need to install a separate package.

Node FS Rename File – To rename file with Node FS, use fs.rename(new_file_name, old_file_name, callback_function) for asynchronous file rename operation and use fs.renameSync(new_file_name, old_file_name) for synchronous file rename operation. In this Node.js Tutorial, we shall learn syntax and examples for fs.rename() and fs.renameSync() functions of Node FS module.

Important parameter order: In the current Node.js FS API, the first argument is the existing path and the second argument is the new path. In other words, use fs.rename(oldPath, newPath, callback). The same order applies to fs.renameSync(oldPath, newPath) and fs.promises.rename(oldPath, newPath).

Correct fs.rename() syntax for renaming a file in Node.js

The syntax of rename() function is

</>
Copy
fs.rename(new_file_path, old_file_path, callback_function)

For practical Node.js code, use the following argument order.

</>
Copy
fs.rename(old_file_path, new_file_path, callback_function)

where

  • old_file_path is the current path of the file that has to be renamed.
  • new_file_path is the new path or new file name that should replace the old path.
  • callback_function runs after the rename operation finishes. It receives an error object as the first argument. If the rename is successful, the error value is null.

fs.rename() renames the file asynchronously. It starts the file system operation and then Node.js continues with the rest of the program. Code that depends on the renamed file should be placed inside the callback or written using promises with await.

Correct fs.renameSync() syntax for synchronous file rename

The syntax of renameSync() function is

</>
Copy
fs.renameSync(new_file_path, old_file_path)

For current Node.js usage, the existing path comes first and the new path comes second.

</>
Copy
fs.renameSync(old_file_path, new_file_path)

fs.renameSync() renames the file synchronously. This means the current thread is blocked until the rename operation completes or fails. It is simple to use in small scripts, but it should be used carefully in server request handlers because it can block other work.

Example 1 – Rename file Asynchronously

In this example, the file is renamed asynchronously from sample.txt to sample_old.txt.

To rename a file asynchronously in Node.js using Node FS, use rename() function as shown below.

nodejs-rename-file.js

</>
Copy
var fs = require('fs');

fs.rename('sample.txt', 'sample_old.txt', function (err) {
  if (err) throw err;
  console.log('File Renamed.');
});

Open a terminal or command prompt and run this script using node command as shown in the following.

Output

arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-rename-file.js 
File Renamed.

When you rename a file asynchronously, do not write code that assumes the rename has already finished on the next line. If you need to read the file, delete the file, move it again, or send a response after the rename, do that work inside the callback.

</>
Copy
const fs = require('fs');

fs.rename('sample.txt', 'sample_old.txt', function (err) {
  if (err) {
    console.error('Rename failed:', err.message);
    return;
  }

  console.log('The file is now available as sample_old.txt');
});

If there are no further tasks related to the file after renaming, rename file asynchronously, else rename it synchronously.

A more flexible rule is: use fs.rename() or fs.promises.rename() for most application code, and put dependent work after the callback or after await. Use fs.renameSync() mainly for short command-line scripts, setup scripts, or cases where blocking behavior is acceptable.

Example 2 – Rename file synchronously with fs.renameSync()

In this example, the file is renamed synchronously from sample.txt to sample_old.txt.

To rename a file synchronously in Node.js using Node FS, use renameSync() function as shown below.

nodejs-rename-file.js

</>
Copy
var fs = require('fs');

fs.renameSync('sample.txt', 'sample_old.txt');
console.log('File Renamed.');

Open a terminal or command prompt and run this script using node command as shown in the following.

Output

arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-rename-file.js 
File Renamed.

Because fs.renameSync() throws an exception when the operation fails, wrap it in try...catch if the file might be missing, locked, or unavailable.

</>
Copy
const fs = require('fs');

try {
  fs.renameSync('sample.txt', 'sample_old.txt');
  console.log('File Renamed.');
} catch (err) {
  console.error('Rename failed:', err.message);
}

Rename a file with fs.promises.rename() and async await

Modern Node.js code often uses the promise-based FS API because it works cleanly with async and await. This avoids nested callbacks while keeping the rename operation asynchronous.

nodejs-rename-file-promise.js

</>
Copy
const fs = require('fs/promises');

async function renameFile() {
  try {
    await fs.rename('sample.txt', 'sample_old.txt');
    console.log('File Renamed.');
  } catch (err) {
    console.error('Rename failed:', err.message);
  }
}

renameFile();

This version is usually preferred when you are already writing promise-based code. The file is renamed from sample.txt to sample_old.txt, and any error is handled in the catch block.

Rename a file inside a folder using Node.js path module

If the file is inside a folder, build the file path with the Node.js path module instead of manually joining strings. This makes the code safer across Windows, Linux, and macOS path formats.

</>
Copy
const fs = require('fs/promises');
const path = require('path');

async function renameReport() {
  const oldPath = path.join(__dirname, 'reports', 'draft-report.txt');
  const newPath = path.join(__dirname, 'reports', 'final-report.txt');

  try {
    await fs.rename(oldPath, newPath);
    console.log('Report renamed successfully.');
  } catch (err) {
    console.error('Could not rename report:', err.message);
  }
}

renameReport();

Here, only the file name changes. The file remains in the same reports folder. If the new path points to a different folder on the same file system, fs.rename() can also move the file while renaming it.

Move and rename a file with fs.rename()

fs.rename() is not limited to changing only the last part of a file name. When the new path includes a different directory, Node.js attempts to move the file to that directory and apply the new name.

</>
Copy
const fs = require('fs/promises');
const path = require('path');

async function moveAndRenameFile() {
  const oldPath = path.join(__dirname, 'incoming', 'data.txt');
  const newPath = path.join(__dirname, 'processed', 'data-processed.txt');

  try {
    await fs.rename(oldPath, newPath);
    console.log('File moved and renamed.');
  } catch (err) {
    console.error('Move and rename failed:', err.message);
  }
}

moveAndRenameFile();

The destination folder must already exist. If processed does not exist, the rename operation fails with an error such as ENOENT.

Common fs.rename() errors when renaming files in Node.js

File rename failures are common when the source path, destination path, or file permissions are not correct. Handle these errors instead of assuming the rename will always succeed.

Error codeMeaning during file renameWhat to check
ENOENTThe source file or destination folder was not found.Check spelling, relative path, working directory, and whether the destination folder exists.
EACCES or EPERMThe process does not have permission to rename the file.Check file permissions, folder permissions, and whether another process is locking the file.
EXDEVThe rename crosses file system boundaries.Use copy and delete logic when moving across different devices or mounted file systems.
EEXISTA conflicting destination path exists in a situation where the platform does not allow replacement.Check whether the destination file already exists and decide whether to overwrite, skip, or create a unique name.

Behavior can vary by operating system when the destination file already exists. For safer application logic, check your expected overwrite behavior and test it on the operating systems where your Node.js program will run.

Rename many files in a directory with Node.js

To rename multiple files, read the directory, loop through the file names, and call fs.rename() for each file. The following example adds the prefix backup- to every .txt file in a folder.

</>
Copy
const fs = require('fs/promises');
const path = require('path');

async function renameTextFiles() {
  const folderPath = path.join(__dirname, 'notes');
  const files = await fs.readdir(folderPath);

  for (const file of files) {
    if (!file.endsWith('.txt')) {
      continue;
    }

    const oldPath = path.join(folderPath, file);
    const newPath = path.join(folderPath, `backup-${file}`);

    await fs.rename(oldPath, newPath);
  }

  console.log('Text files renamed.');
}

renameTextFiles().catch(function (err) {
  console.error('Batch rename failed:', err.message);
});

For bulk rename scripts, test with a small folder first. It is also a good practice to print the old and new paths before renaming files, especially when file names are generated dynamically.

fs.rename() vs fs.renameSync() in Node.js

MethodExecution styleError handlingBest used for
fs.rename()Asynchronous callbackError is passed to the callback.Applications that should not block while the file system operation runs.
fs.promises.rename()Asynchronous promiseError is caught with try...catch when using await.Modern async code and scripts that already use promises.
fs.renameSync()Synchronous blocking callError is thrown as an exception.Small scripts, setup tasks, and cases where blocking is acceptable.

For most server-side Node.js applications, prefer the asynchronous versions. They allow the event loop to keep handling other work while the file system operation is pending.

FAQ on Node.js file rename using FS module

What does fs.rename() do in Node.js?

fs.rename() changes the path of a file or directory. If the old and new paths are in the same folder, it effectively renames the file. If the new path is in another folder on the same file system, it can move the file as well.

What is the correct argument order for fs.rename()?

The correct order is fs.rename(oldPath, newPath, callback). The first path is the current file path, and the second path is the new file path.

Should I use fs.rename() or fs.renameSync()?

Use fs.rename() or fs.promises.rename() for non-blocking application code. Use fs.renameSync() only when blocking the process is acceptable, such as in a small command-line utility or setup script.

Can fs.rename() overwrite an existing file?

It may replace an existing file in some common cases, but behavior can depend on the operating system and the type of destination path. If overwriting matters in your program, check whether the destination exists and handle that case deliberately.

Can fs.rename() rename a file across different drives?

Renaming across different file systems or drives can fail with an EXDEV error. In that case, copy the file to the destination and then delete the original after the copy succeeds.

Editorial QA checklist for this Node FS rename tutorial

  • Confirm that every new Node.js rename example uses oldPath first and newPath second.
  • Verify that asynchronous examples do dependent work inside the callback or after await.
  • Check that synchronous examples explain blocking behavior and include try...catch where failure is possible.
  • Test folder-based examples with destination folders that already exist.
  • Review batch rename examples carefully before running them on real files, because bulk renaming can be difficult to undo.

Conclusion

Node FS Rename File – We have learnt to rename a file synchronously and asynchronously with the help of examples using rename() and renameSync() functions of Node FS.

In practical Node.js programs, remember the path order: existing path first, new path second. Use fs.promises.rename() or fs.rename() for non-blocking code, use fs.renameSync() only when blocking is acceptable, and always handle file system errors such as missing files, missing folders, and permission issues.