In this article, we will create a directory using NodeJS.
NodeJS has Filesystem(fs) core module, which enables interacting with the file system, has Node.js fs.mkdir() method or Node.js fs.mkdirSync() method method, to create new directory /parent directory.
Node.js fs.mkdir() method: Let’s create a new directory using fs.mkdir() method. Initially, we have single file index.js, as we can see in the given image.
Example: Edit the index.js file.
- You can check the terminal output.
- After executing the above code, node.js will create a new directory if it does not exist. A new Directory named — “new-Directory” is created.
Creating Parent Directories: If we want to create multilevel directory, fs.mkdir() has optional recursive Boolean value we can pass as a parameter.
- New Directory created successfully.
We can see that a multilevel directory “directory1\directory2\new-directory” is created.
Removing a folder: If we want to delete a given directory, we can use Node.js fs.rmdir() Method or Node.js fs.rmdirSync() Method, it will become complicated if the directory contain some file content.
So we can use a third party package fs-extra provided by npm to delete the given directory. Let’s install the given package using npm.
Run the following command in your command line
npm install fs-extra
Example: Now run the following code to delete the given directory
Node.js fs.mkdirSync() method: Let’s create a new directory using fs.mkdirSync() method. Initially, we have single file index.js, as we can see in the given image.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.