Node fs.rename() Method
Last Updated :
18 Jan, 2024
The `fs.rename()` method is employed for the asynchronous renaming of a file, moving it from the specified old path to a designated new path. If a file already exists at the new path, it will be overwritten by the operation.
Syntax:
fs.rename( oldPath, newPath, callback )
Parameters: This method accepts three 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.
- callback: It is the function that would be called when the method is executed. It has an optional argument for showing any error that occurs during the process.
Example 1: Below examples illustrate the fs.rename() method in Node.js:
Javascript
const fs = require( 'fs' );
getCurrentFilenames();
fs.rename(
'hello.txt' ,
'world.txt' ,
() => {
console.log( "\nFile Renamed!\n" );
getCurrentFilenames();
});
function getCurrentFilenames() {
console.log( "Current filenames:" );
fs.readdirSync(__dirname)
.forEach(file => {
console.log(file);
});
}
|
Output:
Current filenames:
hello.txt
index.js
File Renamed!
Current filenames:
index.js
world.txt
Example 2: This example uses fs.rename() method to demonstrate an error during file renaming.
Javascript
const fs = require( 'fs' );
getCurrentFilenames();
fs.rename( 'hello.txt' , 'geeks.txt' ,
(error) => {
if (error) {
console.log(error);
}
else {
console.log( "\nFile Renamed\n" );
getCurrentFilenames();
}
});
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\hello.txt' ->
'G:\tutorials\nodejs-fs-rename\geeks.txt'] {
errno: -4058,
code: 'ENOENT',
syscall: 'rename',
path: 'G:\\tutorials\\nodejs-fs-rename\\hello.txt',
dest: 'G:\\tutorials\\nodejs-fs-rename\\geeks.txt'
}
We have a complete reference article on File System methods, where we have covered all the File System methods to check those please go through File System Complete Reference article
Share your thoughts in the comments
Please Login to comment...