
fs.mkdir can be used to create a directory asynchronously which basically means that other async logic in the script may run before or after fs.mkdir. In this example, sometimes the foo directory would be created first and the bar directory would be created second. Other times, the bar directory would be created first and the foo directory would be created second.
const fs = require("fs")
const foo = "/tmp/foo"
const bar = "/tmp/bar"
fs.mkdir(foo, { recursive: true }, (err) => {
if (err) {
console.error(err)
} else {
console.log(`Successfully created the ${foo} directory`)
}
})
fs.mkdir(bar, { recursive: true }, (err) => {
if (err) {
console.error(err)
} else {
console.log(`Successfully created the ${bar} directory`)
}
})
Be aware that if you are using a Node.js module instead of CommonJS, you will have "type": "module" in package.json. In this scenario, you will use import instead of require.
import fs from "fs"
fs.mkdirSync can be used to create a directory synchronously which basically means that the script reads like a book, from the top of the script to the bottom of the script, doing things in the order. In this example, the foo directory would always be created first and the bar directory would always be created second.
import fs from "fs"
const foo = "/tmp/foo"
const bar = "/tmp/bar"
fs.mkdirSync(foo, { recursive: true }, (err) => {
if (err) {
console.error(err)
} else {
console.log(`Successfully created the ${foo} directory`)
}
})
fs.mkdirSync(bar, { recursive: true }, (err) => {
if (err) {
console.error(err)
} else {
console.log(`Successfully created the ${bar} directory`)
}
})
You may want to also include fs.existsSync to determine if the directory already exists.
import fs from "fs"
const foo = "/tmp/foo"
if (fs.exists(foo )) {
console.warn(`The ${foo} directory already exists`)
} else {
fs.mkdir(foo, { recursive: true }, (err) => {
if (err) {
console.error(err)
} else {
console.log(`Successfully created the ${foo} directory`)
}
})
}
Did you find this article helpful?
If so, consider buying me a coffee over at