How to rename a file asynchronously in Node.js?

Published December 23, 2020

To rename a file asynchronously, you can use the rename() function from the fs (filesystem) module in Nodejs.

// Rename file asynchronously
fs.rename("file.txt", "myFile.txt", () => {
  console.log("Successfully renamed!");
});

Let's say you want to rename a file called file.txt inside the docs directory, so the path now looks like this,

// path to rename
const path = "./docs/file.txt";

Let's rename the file.txt to myfile.txt. So let's create another variable to hold the new filename path like this,

// path to rename
const path = "./docs/file.txt";

// new file name
const newFileNamePath = "./docs/myFile.txt";

Now we can use the rename() asynchronous function and pass:

  • the path as the first argument
  • and the newFileNamePath as the second argument
  • and finally, an error first callback that will execute after the file is renamed.

It can be done like this,

// require fs module
const fs = require("fs");

// path to rename
const path = "./docs/file.txt";

// new file name
const newFileNamePath = "./docs/myFile.txt";

// rename file.txt to myFile.txt
// using the rename() asynchronous function
fs.rename(path, newFileNamePath, (error) => {
  if (error) {
    throw error;
  }
  console.log("Successfully Renamed File!");
});

And we have successfully renamed our file 🔥.

See this example live in repl.it.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter