snippetjavascriptTip
Create a directory if it doesn't exist using Node.js
Viewed 0 times
javascriptnodedirectoryexistusingdoesncreate
Problem
When working with files and directories in Node.js, you might want to create a directory, if it doesn't exist yet. The default behavior of the filesystem methods in Node.js is to throw an error if the directory already exists, so you need to roll up your own solution for this task.
Most commonly, you'll want to create a directory asynchronously, using
While the asynchronous approach is generally preferred, you might want to create a directory synchronously in some cases. You can use
Most commonly, you'll want to create a directory asynchronously, using
fs.mkdir(). This method returns a Promise, that will reject if the directory already exists. In order to remedy that, we can use fs.access() to check if the directory exists, and then create it if it doesn't.While the asynchronous approach is generally preferred, you might want to create a directory synchronously in some cases. You can use
fs.existsSync() to check if the directory exists, and fs.mkdirSync() to create it.Solution
import { access, mkdir } from 'fs/promises';
const createDirIfNotExists = dir =>
access(dir)
.then(() => undefined)
.catch(() => mkdir(dir));
createDirIfNotExists('test');
// Asynchronously creates the directory 'test', if it doesn't existWhile the asynchronous approach is generally preferred, you might want to create a directory synchronously in some cases. You can use
fs.existsSync() to check if the directory exists, and fs.mkdirSync() to create it.Code Snippets
import { access, mkdir } from 'fs/promises';
const createDirIfNotExists = dir =>
access(dir)
.then(() => undefined)
.catch(() => mkdir(dir));
createDirIfNotExists('test');
// Asynchronously creates the directory 'test', if it doesn't existimport { existsSync, mkdirSync } from 'fs';
const createDirIfNotExists = dir =>
!existsSync(dir) ? mkdirSync(dir) : undefined;
createDirIfNotExists('test');
// Synchronously creates the directory 'test', if it doesn't existContext
From 30-seconds-of-code: create-directory-if-not-exists
Revisions (0)
No revisions yet.