EN
Node.js - create directory using path
0 points
In this article, we would like to show you how to create directory / folder using fs.mkdirSync
method in Node.js.
Quick solution:
xxxxxxxxxx
1
const fs = require('fs');
2
3
const directoryPath = './newFolder';
4
5
if (!fs.existsSync(directoryPath)) {
6
fs.mkdirSync(directoryPath);
7
}
8
In this example, we create a new folder under the given path.
xxxxxxxxxx
1
const fs = require('fs');
2
3
const directoryPath = './newFolder';
4
5
if (!fs.existsSync(directoryPath)) {
6
fs.mkdirSync(directoryPath);
7
} else {
8
console.log('File or directory already exist!');
9
}
if we want to create folders that are nested, we have to set the recursive flag in the mkdirSync()
method.
xxxxxxxxxx
1
const fs = require('fs');
2
3
const directoryPath = 'C:/projects/example/newFolder';
4
5
if (!fs.existsSync(directoryPath)) {
6
fs.mkdirSync(directoryPath, { recursive: true });
7
} else {
8
console.log('File or directory already exist!');
9
}
Result:
