DEV Community

Cover image for How to rename a file asynchronously in Node.js?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to rename a file asynchronously in Node.js?

Originally posted here!

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!");
});
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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!");
});
Enter fullscreen mode Exit fullscreen mode

And we have successfully renamed our file 🔥.

See this example live in repl.it.

Feel free to share if you found this useful 😃.


Top comments (0)