Open In App

Node.js fs.renameSync() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The fs.renameSync() method is used to synchronously rename a file at the given old path to the given new path. It will overwrite the destination file if it already exists.

Syntax:

fs.renameSync( oldPath, newPath )

Property Values:

  • 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 to. It can be a string, buffer or URL.

Below examples illustrate the fs.renameSync() method in Node.js:

Example 1: This example uses fs.renameSync() method to rename a file.




// Node.js program to demonstrate the
// fs.renameSync() method
  
// Import the filesystem module
const fs = require('fs');
  
// List all the filenames before renaming
getCurrentFilenames();
  
// Rename the file
fs.renameSync('hello.txt', 'world.txt');
  
// List all the filenames after renaming
getCurrentFilenames();
  
// function to get current filenames in directory
function getCurrentFilenames() {
  console.log("Current filenames:");
  fs.readdirSync(__dirname).forEach(file => {
    console.log(file);
  });
}


Output:

Current filenames:
hello.txt
index.js
package.json
Current filenames:
index.js
package.json
world.txt

Example 2: This example uses fs.renameSync() method to demonstrate an error during file renaming.




// Node.js program to demonstrate the
// fs.renameSync() method
  
// Import the filesystem module
const fs = require('fs');
  
// List all the filenames before renaming
getCurrentFilenames();
  
// Rename a non-existent file
fs.renameSync('nonexist.txt', 'world.txt');
  
// List all the filenames after renaming
getCurrentFilenames();
  
// 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
internal/fs/utils.js:220
    throw err;
    ^

Error: ENOENT: no such file or directory, rename 'nonexist.txt' -> 'world.txt'
    at Object.renameSync (fs.js:643:3)
    at Object. (G:\tutorials\nodejs-fs-renameSync\index.js:29:4)
    at Module._compile (internal/modules/cjs/loader.js:956:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
    at internal/main/run_main_module.js:17:11 {
  errno: -4058,
  syscall: 'rename',
  code: 'ENOENT',
  path: 'nonexist.txt',
  dest: 'world.txt'
}

Reference: https://nodejs.org/api/fs.html#fs_fs_renamesync_oldpath_newpath



Last Updated : 12 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads