var filessystem = require('fs');var dir = './path/subpath/';
if (!filessystem.existsSync(dir)){filessystem.mkdirSync(dir);}else{console.log("Directory already exist");}
const createDir = (dir) => {// This will create a dir given a path such as './folder/subfolder'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}, '')}
// importconst fs = require('fs') // In JavaScriptimport * as fs from "fs" // in TypeScriptimport fs from "fs" // in Typescript
// Use!fs.existsSync(`./assets/`) && fs.mkdirSync(`./assets/`, { recursive: true })
// First require fsconst fs = require('fs');
// Create directory if not exist (function)const createDir = (path) => {// Check if dir existfs.stat(path, (err, stats) => {if (stats.isDirectory()) {// Do nothing} else {// If the given path is not a directory, create a directoryfs.mkdirSync(path);}});};
var fs = require("fs");
var dir = __dirname + '/upload';
// if (!fs.existsSync(dir)) {// fs.mkdirSync(dir);// }
if (!fs.existsSync(dir)) {fs.mkdirSync(dir, {mode: 0o744,});// mode's default value is 0o744}
ESM
更新package.json配置
{//..."type": "module",//...}
import fs from "fs";import path from "path";
// create one custom `__dirname`, because it not exist in es-module env ⚠️const __dirname = path.resolve();
const dir = __dirname + '/upload';
if (!fs.existsSync(dir)) {fs.mkdirSync(dir);}
// ORif (!fs.existsSync(dir)) {fs.mkdirSync(dir, {mode: 0o744,});// mode's default value is 0o744}
const fs = require('fs');const path = require('path');
const dir = path.resolve(path.join(__dirname, 'upload');
if (!fs.existsSync(dir)) {fs.mkdirSync(dir);}
// ORif (!fs.existsSync(dir)) {fs.mkdirSync(dir, {mode: 0o744, // Not supported on Windows. Default: 0o777});}
ESM
更新您的package.json文件配置
{// declare using ECMAScript modules(ESM)"type": "module",//...}
import fs from 'fs';import path from 'path';import { fileURLToPath } from 'url';
// create one custom `__dirname`, because it does not exist in es-module env ⚠️const __filename = fileURLToPath(import.meta.url);const __dirname = path.dirname(__filename);const dir = path.resolve(path.join(__dirname, 'upload');
if (!fs.existsSync(dir)) {fs.mkdirSync(dir);}
// ORif (!fs.existsSync(dir)) {fs.mkdirSync(dir, {mode: 0o744, // Not supported on Windows. Default: 0o777});}
fsNative.mkdir(dirPath,{recursive:true},(err) => {if(err) {//note: this does NOT get triggered if the directory already existedconsole.warn(err)}else{//directory now exists}})
import * as fs from 'fs/promises';
await fs.mkdir(dirPath, {recursive:true}).catch((err) => {//decide what you want to do if this failedconsole.error(err);});
//directory now exists