Open In App

How to operate callback-based fs.rename() method with promises in Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

The fs.rename() method is defined in the File System module of Node.js. The File System module is basically to interact with hard-disk of the user’s computer. The rename() method is used to rename the file at the given old path to a given new path. If the new path file already exists, it will be overwritten and if there exists a directory at new path, an error occurs.

The fs.rename() method is based on callback. Using callback methods leads to a great chance of callback nesting or callback hell problems. Thus to avoid it we almost always like to work with promise based method. Using some extra node.js methods we can operate a callback-based method in promise way.

Syntax:

fs.rename(oldPath, newPath)

Note: Callback not required if we operate the method with promises.

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

  • oldpath: It is a String, Buffer or URL that specifies the path to the file that has to be renamed.
  • newpath: It is a String, Buffer or URL that specifies the path to the file from which old file is going to replace.

Approach: The fs.rename() method based on callback. To operate it with promises, first, we use promisify() method defined in utilities module to convert it into a promise based method.

Example 1: Filename: index.js




// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to promise
// based methods
const readDir = util.promisify(fs.readdir)
const rename = util.promisify(fs.rename)
   
readDir(process.cwd())
.then(files => {
  console.log(`Contents before rename operation: `)
       
  // Contents of the current directory
  for(let file of files) {
      console.log(file)
  }
   
  console.log('\nAttempt to rename file : \n')
    
  // Rename operation
  return rename('test.txt', 'testFile.txt')
})
   
.then(() => {
  
  // The process.cwd() gives current working
  // directory
  return readDir(process.cwd())
})
   
.then(files => {
  console.log(`Contents after rename operation: `)
    
  // Contents of the current directory
  for(let file of files) {
    console.log(file)
  }
})
  
.catch(err => {
   console.log(`Error occurs, 
   Error code -> ${err.code}, 
   Error No -> ${err.errno}`);
})


Implementing the same functionality using async-await.




// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to promise
// based methods
const readDir = util.promisify(fs.readdir)
const rename = util.promisify(fs.rename)
   
const renameOperation = async (oldpath, newpath) => {
  console.log(`Contents before rename operation: `)
     
  // Fetching contents of the directory before
  // rename operation. The process.cwd() gives
  // current working directory
  const oldFiles = await 
      fs.promises.readdir(process.cwd())
   
  // Contents of the current working directory
  for(let file of oldFiles){
    console.log(file)
  }
   
  console.log('\nAttempt to rename file : \n')
   
  // Rename operation
  await fs.promises.rename(oldpath, newpath)
  console.log(`Contents after rename operation: `)
     
  // Fetching contents of directory before
  // rename operation
  const newFiles = await 
      fs.promises.readdir(process.cwd())
    
  // Contents of the current working directory
  for(let file of newFiles) {
    console.log(file)
  }
}
   
renameOperation('test.txt', 'testFile.txt')
.catch(err => {
  console.log(`Error occurs, Error code -> ${err.code}, 
  Error No -> ${err.errno}`);
});


Run index.js file using the following command:

node index.js

The directory structure before running the program:

The directory structure after running the program:

Output:

Example 2: When given newpath is not the path to a file but a directory.
Filename: index.js




// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to promise
// based methods
const readDir = util.promisify(fs.readdir)
const rename = util.promisify(fs.rename)
   
readDir(process.cwd())
.then(files => {
  console.log(`Contents before rename operation: `)
       
  // Contents of the current directory
  for(let file of files) {
    console.log(file)
  }
   
  console.log('\nAttempt to rename file : \n')
    
  // Rename operation
  return rename('testFile.txt', 'test')
})
   
.then(() => {
  
  // The process.cwd() gives current 
  // working directory
  return readDir(process.cwd())
})
   
.then(files => {
  console.log(`Contents after rename operation: `)
    
  // Contents of the current directory
  for(let file of files) {
    console.log(file)
  }
})
  
.catch(err => {
   console.log(`Error occurs, 
   Error code -> ${err.code}, 
   Error No -> ${err.errno}`);
})


Implementing the same functionality with async-await.




// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to promise
// based methods
const readDir = util.promisify(fs.readdir)
const rename = util.promisify(fs.rename)
  
   
const renameOperation = async (oldpath, newpath) => {
  console.log(`Contents before rename operation: `)
     
  // Fetching contents of directory before 
  // rename operation. The process.cwd() 
  // gives current working directory
  const oldFiles = await readDir(process.cwd())
   
  // Contents of the current working directory
  for(let file of oldFiles) {
    console.log(file)
  }
   
  console.log('\nAttempt to rename file : \n')
    
  // Rename operation
  await rename(oldpath, newpath)
    
  console.log(`Contents after rename operation: `)
     
  // Fetching contents of directory before rename operation
  const newFiles = await readDir(process.cwd())
    
  // Contents of the current working directory
  for(let file of newFiles) {
    console.log(file)
  }
}
   
renameOperation('testFile.txt', 'test')
.catch(err => {
   console.log(`Error occurs, 
   Error code -> ${err.code}, 
   Error No -> ${err.errno}`);
});


Run index.js file using the following command:

node index.js

Output:



Last Updated : 18 Jul, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads