The fsPromises.rename() method is used to asynchronously rename a file at the given old path to a given new path. It will overwrite the destination file if it already exists. It resolves the Promise with no arguments upon success.
Syntax:
fsPromises.rename( oldPath, newPath )
Parameters: This method accept two parameters as mentioned above and described below:
- oldPath: It holds the path of the file that has to be renamed. It can be a string, buffer or URL.
- newPath: It holds the new path that the file has to be renamed. It can be a string, buffer or URL.
Below examples illustrate the fsPromises.rename() method in Node.js:
Example 1: This example uses fsPromises.rename() method to rename a file:
// Node.js program to demonstrate the
// fsPromises.rename() method
// Import filesystem module
const fs = require('fs');
const fsPromises = require('fs').promises;
// List all the filenames before renaming
getCurrentFilenames();
(async function main() {
try {
// Rename the file
fsPromises.rename('GFG.txt', 'GeeksforGeeks.txt')
console.log("\nFile Renamed!\n");
// List all the filenames after renaming
getCurrentFilenames();
} catch (err) {
console.error(err);
}
})();
// Function to get current filenames
// in directory
function getCurrentFilenames() {
console.log("Current filenames:");
fs.readdirSync(__dirname).forEach(file => {
console.log(file);
});
}
Output:
Current filenames: GFG.txt GeeksforGeeks.js File Renamed! Current filenames: GeeksforGeeks.js GFG.txt
Example 2: This example uses fsPromises.rename() method to demonstrate an error during file renaming:
// Node.js program to demonstrate the
// fsPromises.rename() method
// Import filesystem module
const fs = require('fs');
const fsPromises = require('fs').promises;
(async function main() {
try {
// List all the filenames before renaming
getCurrentFilenames();
// Rename the file
fsPromises.rename('GeeksforGeeks.txt', 'geeks.txt')
// List all the filenames after renaming
console.log("\nFile Renamed\n");
// List all the filenames after renaming
getCurrentFilenames();
}
catch (err) {
console.error(err);
}
})();
// Function to get current filenames
// in directory
function getCurrentFilenames() {
console.log("Current filenames:");
fs.readdirSync(__dirname).forEach(file => {
console.log(file);
});
}
Output:
Current filenames:
index.js
package.json
world.txt
[Error: ENOENT: no such file or directory, rename
'G:\tutorials\nodejs-fs-rename\GeeksforGeeks.txt' ->
'G:\tutorials\nodejs-fs-rename\geeks.txt'] {
errno: -4058,
code: 'ENOENT',
syscall: 'rename',
path: 'G:\\tutorials\\nodejs-fs-rename\\GeeksforGeeks.txt',
dest: 'G:\\tutorials\\nodejs-fs-rename\\geeks.txt'
}
Reference: https://nodejs.org/api/fs.html#fs_fspromises_rename_oldpath_newpath