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
// 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' , 'w3wiki.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 w3wiki.js File Renamed! Current filenames: w3wiki.js GFG.txt
Example 2: This example uses fsPromises.rename() method to demonstrate an error during file renaming:
Node.js
// 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( 'w3wiki.txt' , 'Beginner.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\w3wiki.txt' -> 'G:\tutorials\nodejs-fs-rename\Beginner.txt'] { errno: -4058, code: 'ENOENT', syscall: 'rename', path: 'G:\\tutorials\\nodejs-fs-rename\\w3wiki.txt', dest: 'G:\\tutorials\\nodejs-fs-rename\\Beginner.txt' }
Reference: https://nodejs.org/api/fs.html#fs_fspromises_rename_oldpath_newpath
Contact Us