Node.js Rename a Directory Tutorial
Method 1: Using the fs.rename
Method
The fs.rename
method is a built-in function in the Node.js fs
(File System) module, and it’s used to change the name of a directory in Node.js. To illustrate, here’s an example of how to rename a directory in Node.js:
const fs = require('fs'); const oldDirectoryName = 'old_directory_name'; const newDirectoryName = 'new_directory_name'; fs.rename(oldDirectoryName, newDirectoryName, (err) => { if (err) { console.error('Error renaming the directory:', err); } else { console.log('Directory renamed successfully!'); } });
Method 2: Using Promises with fs.promises.rename
(Node.js 10.0.0 and later)
If you like using Promises for handling asynchronous tasks, there’s a method called fs.promises.rename
available in Node.js starting from version 10.0.0. You can use it like this:
const fs = require('fs').promises; async function renameDirectory(oldDirectoryName, newDirectoryName) { try { await fs.rename(oldDirectoryName, newDirectoryName); console.log('Directory renamed successfully'); } catch (err) { console.error(`Error renaming directory: ${err}`); } } renameDirectory('old_directory_name', 'new_directory_name');
Method 3: Using the fs-extra
library
npm install fs-extra
Here is an example of how to rename a directory in Node.js using fs extra library:
const fs = require('fs-extra'); const oldDirectoryName = 'old_directory_name'; const newDirectoryName = 'new_directory_name'; fs.move(oldDirectoryName, newDirectoryName, (err) => { if (err) { console.error(`Error renaming directory: ${err}`); } else { console.log('Directory renamed successfully'); } });
Conclusion
You’ve learned three methods to rename a directory in Node.js using the fs.rename(), fs.promises.rename
(),fs-extra
Library. Choose the method that best suits your project’s requirements and Node.js version.