To rename a file synchronously, you can use the renameSync()
function from the fs
(filesystem) module in Nodejs.
// Rename file synchronously
fs.renameSync("file.txt", "myFile.txt");
Let's say you want to rename a file called file.txt
inside the docs
directory, so the path
to it 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 renameSync()
synchronous function and pass:
- the
path
as the first argument - and the
newFileNamePath
as the second argument
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 renameSync() synchronous function
fs.renameSync(path, newFileNamePath);
And we have successfully renamed our file 🔥.
See this example live in repl.it.