How to create a folder in Node.js
Short answer
mkdir() with recursive: true creates all missing folders in the path and does not complain if they already exist:
import { mkdir, stat } from 'node:fs/promises';
await mkdir('storage/cache/images', { recursive: true });
await mkdir('storage/cache/images', { recursive: true });
console.log((await stat('storage/cache/images')).isDirectory());Output:
trueA temporary folder
mkdtemp() creates a folder with a unique name in the system temporary directory:
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, basename } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'upload-'));
console.log(basename(dir).startsWith('upload-'));
await rm(dir, { recursive: true });Output:
trueRemoving a folder
rm() with recursive: true removes a folder with everything inside. Be careful with it: there is no recycle bin.
import { mkdir, rm, writeFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
await mkdir('old-build', { recursive: true });
await writeFile('old-build/app.js', '');
await rm('old-build', { recursive: true, force: true });
console.log(existsSync('old-build'));Output:
falseCommon mistake
Without recursive, mkdir() fails if the parent folder is missing or the folder already exists:
import { mkdir } from 'node:fs/promises';
try {
await mkdir('a/b/c');
} catch (error) {
console.log(error.code);
}Output:
ENOENTFunctions used in this recipe
- await — Waits for a promise and returns its value.