Node.js fsPromises.rename() Method
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
const fs = require( 'fs' );
const fsPromises = require( 'fs' ).promises;
getCurrentFilenames();
(async function main() {
try {
fsPromises.rename( 'GFG.txt' , 'GeeksforGeeks.txt' )
console.log( "\nFile Renamed!\n" );
getCurrentFilenames();
} catch (err) {
console.error(err);
}
})();
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
const fs = require( 'fs' );
const fsPromises = require( 'fs' ).promises;
(async function main() {
try {
getCurrentFilenames();
fsPromises.rename( 'GeeksforGeeks.txt' , 'geeks.txt' )
console.log( "\nFile Renamed\n" );
getCurrentFilenames();
}
catch (err) {
console.error(err);
}
})();
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
Last Updated :
08 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...