You may need to rename files and folders in you Node.js application to make room for new data, archive old data, or apply changes made by a user. Renaming files and folders uses the following fs
calls:
fs.rename(oldPath, newPath, callback)
fs.renameSync(oldPath, newPath)
The oldPath
parameter specifies the existing file or directory path, and the newPath
parameter specifies the new name. The renameSync(path)
function returns true
or false
, depending on whether the file or directory was successfully renamed. On the other hand, an asynchronous rename()
call passes an error value to the callback function if an error is encountered when renaming the file or directory.
The following code snippet illustrates how to implement fs
calls to rename a file named old.txt
to new.txt
and a directory named testDir
to renamedDir
:
fs.rename("old.txt", "new.txt", function(err){
console.log(err ? "Rename Failed" : "File Renamed");
});
fs.rename("testDir", "renamedDir", function(err){
console.log(err ? "Rename Failed" : "Folder Renamed");
});