1149 Stimmen

Wie man ein Verzeichnis erstellt, wenn es mit Node.js nicht existiert

Ist dies der richtige Weg, um ein Verzeichnis zu erstellen, wenn es nicht existiert?

Es sollte volle Berechtigung für das Skript haben und von anderen lesbar sein.

var dir = __dirname + '/upload';
if (!path.existsSync(dir)) {
    fs.mkdirSync(dir, 0744);
}

1voto

xgqfrms Punkte 7010

Meine Lösungen

  1. CommonJS

    var fs = require("fs");

    var dir = __dirname + '/upload';

    // if (!fs.existsSync(dir)) { // fs.mkdirSync(dir); // }

    if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { mode: 0o744, }); // Standardwert für 'mode' ist 0o744 }

  2. ESM

update package.json Konfiguration

{
  //...
  "type": "module",
  //...
}

import fs from "fs";
import path from "path";

// erstelle ein individuelles `__dirname`, da es in einem ES-Modul-Umfeld nicht existiert
const __dirname = path.resolve();

const dir = __dirname + '/upload';

if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir);
}

// ODER
if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir, {
    mode: 0o744,
  });
  // Standardwert für 'mode' ist 0o744
}

Verweise

https://nodejs.org/api/fs.html#fsexistssyncpath

https://github.com/nodejs/help/issues/2907#issuecomment-671782092

1voto

MrBlenny Punkte 565

Hier ist eine kleine Funktion zum rekursiven Erstellen von Verzeichnissen:

const createDir = (dir) => {
  // Dies erstellt ein Verzeichnis basierend auf einem Pfad wie z.B. './Ordner/Unterordner' 
  const splitPath = dir.split('/');
  splitPath.reduce((path, subPath) => {
    let currentPath;
    if(subPath != '.'){
      currentPath = path + '/' + subPath;
      if (!fs.existsSync(currentPath)){
        fs.mkdirSync(currentPath);
      }
    }
    else{
      currentPath = subPath;
    }
    return currentPath
  }, '')
}

0voto

sdgfsdh Punkte 28371

Verwendung von async / await:

const mkdirP = async (Verzeichnis) => {
  try {
    return await fs.mkdirAsync(Verzeichnis);
  } catch (error) {
    if (error.code != 'EEXIST') {
      throw e;
    }
  }
};

Sie müssen fs promisify:

import nodeFs from 'fs';
import bluebird from 'bluebird';

const fs = bluebird.promisifyAll(nodeFs);

0voto

Zach Smith Punkte 7633

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)
        })
      )
    }
  }
}

CodeJaeger.com

CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.

Powered by:

X