Create a Directory in Node.js if It Doesn't Exist
In Node.js, you can create a directory if it doesn't exist using the fs (File System) module. Here's how you can do it:
1. Using fs.mkdir:
You can use the fs.mkdir function to create a directory. If the directory already exists, it will throw an error. To handle the case where the directory may or may not exist, you can use the fs.access function to check if the directory exists before attempting to create it.
In this code:
-
We use fs.access to check if the directory exists. If it doesn't exist, it will throw an error, which we catch to create the directory.
-
We use fs.mkdir to create the directory. The recursive: true option ensures that parent directories are created recursively if they don't exist.
Using fs.promises.mkdir (Node.js v10 and above):
If you are using Node.js version 10 or above, you can use the fs.promises API for asynchronous file system operations without using callbacks.
This code achieves the same result as the previous example but uses promises for asynchronous operations.
Conclusion:
Both methods allow you to create a directory if it doesn't exist using Node.js. Choose the method that best fits your coding style and the Node.js version you're targeting.