Rename a File in Node.js using Node FS

Node FS Rename File

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.

  • Syntax of fs.rename()
  • Syntax of fs.renameSync()
  • Example to Rename file Asynchronously
  • Example to Rename file Synchronously

Syntax of rename() function

Following is the syntax of rename() function :

fs.rename(new_file_path, old_file_path, callback_function)

where

new_file_path (is a String and Mandatory) :  The new file path you would like to assign

old_file_path (is a String and Mandatory) : Path to the file whose name is to be changed

callback_function : When file renaming operation is done, Callback Function is called with an error object. (If there is no error, error object holds null value)

 

Syntax of renameSync() function

Following is the syntax of renameSync() function :

fs.renameSync(new_file_path, old_file_path)

 

Example to Rename file Asynchronously

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

Run the program in terminal with node

Please note that when you rename a file asynchronously, it is not guaranteed that the renaming happens immediately. And if you plan some tasks with the renamed file right after the renaming operation like reading file, deleting file etc., it may not execute as expected. So make a thumb rule

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

Synchronous Operation costs execution time. So, based on your requirement, plan to use either rename() or renameSync().

 

Example to Rename file Synchronously

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

Run the program in terminal with node

 

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.