Eine Funktion, um dies asynchron durchzuführen (angepasst von einer ähnlichen Antwort auf SO, die synchrone Funktionen verwendet hat, die ich jetzt nicht finden kann)
// ensure-directory.js
import { mkdir, access } from 'fs'
/**
* directoryPath ist ein Pfad zu einem Verzeichnis (keine abschließende Datei!)
*/
export default async directoryPath => {
directoryPath = directoryPath.replace(/\\/g, '/')
// -- Vorbereitung, um auch absolute Pfade zu erlauben
let root = ''
if (directoryPath[0] === '/') {
root = '/'
directoryPath = directoryPath.slice(1)
} else if (directoryPath[1] === ':') {
root = directoryPath.slice(0, 3) // c:\
directoryPath = directoryPath.slice(3)
}
// -- Ordner bis ganz nach unten erstellen
const folders = directoryPath.split('/')
let folderPath = `${root}`
for (const folder of folders) {
folderPath = `${folderPath}${folder}/`
const folderExists = await new Promise(resolve =>
access(folderPath, error => {
if (error) {
resolve(false)
}
resolve(true)
})
)
if (!folderExists) {
await new Promise((resolve, reject) =>
mkdir(folderPath, error => {
if (error) {
reject('Fehler beim Erstellen von folderPath')
}
resolve(folderPath)
})
)
}
}
}