How to create folder or use existing with Node.js?

Sometimes, we want to create folder or use existing with Node.js.

In this article, we’ll look at how to create folder or use existing with Node.js.

How to create folder or use existing with Node.js?

To create folder or use existing with Node.js, we can use the recursive option with mkdirSync or mkdir.

For instance, we write

fs.mkdirSync(dirpath, {
  recursive: true
})

to create the folder at the path given by dirpath if it doesn’t exists by setting recursive to true with mkdirSync.

mkdirSync creates the folder synchronously.

We can create a folder asynchronously with mkdir by writing

await fs.promises.mkdir(dirpath, {
  recursive: true
})

Conclusion

To create folder or use existing with Node.js, we can use the recursive option with mkdirSync or mkdir.