VOOZH about

URL: https://www.geeksforgeeks.org/node-js/node-js-fspromises-rename-method/

⇱ Node.js fsPromises.rename() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Node.js fsPromises.rename() Method

Last Updated : 8 Oct, 2021

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:

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:

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
Comment

Explore