English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Node FS File Rename– To rename a file using Node FS, use fs.rename(new_file_name, old_file_name, callback_function) is used for asynchronous file renaming operations and uses fs.renameSync(new_file_name, old_file_name) is used for synchronous file renaming operations. In this Node.js tutorial, we will learn the syntax and examples of the Node FS module's fs.rename() and fs.renamesync() functions.
The following is the syntax of the rename() function:
fs.rename(new_file_path, old_file_path, callback_function) |
Function description
new_file_path(Is a string and required): The new file path you want to assign
old_file_path(Is a string and required): The path of the file to be renamed
callback_functionAfter completing the file renaming operation, the callback function will be called with the error object. (If there is no error, the error object remains empty)
Here is the syntax of the renameSync() function:
fs.renameSync(new_file_path, old_file_path) |
To rename a file asynchronously in Node.js using Node FS, use the rename() function as shown below:
var fs = require('fs'); fs.rename('sample.txt', 'sample_old.txt', function (err) { if (err) throw err; console.log('File Renamed.'); });
Run the program in a terminal with nodes
Terminal Output
arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-rename-file.js File Renamed.
Please note that when you rename files asynchronously, you cannot guarantee immediate renaming. Moreover, if you plan to perform some tasks using the renamed file immediately after the renaming operation, such as reading the file, deleting the file, etc., it may not execute as expected. So here is an experience rule
If there are no other tasks related to the file after renaming, rename the file asynchronously; otherwise, rename it synchronously.
Synchronous operations consume execution time. Therefore, plan to use rename() or renameSync() based on your needs.
To rename a file synchronously in Node.js using Node FS, use the renameSync() function as shown below:
var fs = require('fs'); fs.renameSync('sample.txt', 'sample_old.txt'); console.log('File Renamed.');
Run the program in a terminal with nodes
Terminal Output
arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-rename-file.js File Renamed.
Node FS File Rename–We have learned to use the example of the rename() and renameSync() functions of Node FS to rename files synchronously and asynchronously.