Home Node.js Rename a File in Node.js using the File System module

Rename a File in Node.js using the File System module

The fs.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.

Table of Contents

Syntax:

fs.rename( oldPath, newPath, callback )

Parameters: This method accept three parameters as mentioned above and described below:

oldPath: Path to the file whose name is to be changed. It can be a string, buffer or URL.

newPath: The new file path you would like to create. 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. (If there is no error, error object holds null value)

 

Example

I called the file renamefile.js

// include file system module
var fs = require('fs');
 
//rename the file
fs.rename('sample.txt', 'sample_new.txt', function (err) {
  if (err) throw err;
  console.log('File Renamed.');
});

Open a node.js command prompt and run the program like node renamefile.js

This was the output of my file

C:\Users\user\nodejs>node renamefile.js
File Renamed.

Links

Code is in github

https://github.com/programmershelp/maxjavascript/tree/main/nodejs

You may also like