Sometimes, we want to create a directory if it doesn’t exist using Node.js.
In this article, we’ll look at how to create a directory if it doesn’t exist using Node.js.
How to create a directory if it doesn’t exist using Node.js?
To create a directory if it doesn’t exist using Node.js, we can use the existsSync
method to check if a directory exists.
And then we can use the mkdirSync
method to let us create the directory.
For instance, we write
const fs = require('fs');
const dir = './tmp';
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
to require the fs
module.
Then we call fs.existsSync
with dir
to check if a folder with the path given in dir
exists.
If it does, it returns false
.
And we call mkdirSync
with the dir
path to create a directory with the path if the directory doesn’t exist.
Conclusion
To create a directory if it doesn’t exist using Node.js, we can use the existsSync
method to check if a directory exists.
And then we can use the mkdirSync
method to let us create the directory.