How to Use fs.mkdir in Node.js: Create Directories Easily
In Node.js, use
fs.mkdir from the fs/promises module to create directories asynchronously. It accepts the directory path and options like { recursive: true } to create nested folders. Use await mkdir(path, options) inside an async function for clean, modern code.Syntax
The fs.mkdir function creates a new directory. When using the promise version from fs/promises, the syntax is:
path: The folder path to create, as a string.options: Optional object. Use{ recursive: true }to create nested directories.
It returns a promise that resolves when the directory is created or already exists (if recursive).
javascript
import { mkdir } from 'fs/promises'; await mkdir(path, { recursive: true });
Example
This example shows how to create a folder named logs inside the current directory. It uses async/await for clear asynchronous code.
javascript
import { mkdir } from 'fs/promises'; async function createFolder() { try { await mkdir('./logs', { recursive: true }); console.log('Folder created successfully'); } catch (error) { console.error('Error creating folder:', error); } } createFolder();
Output
Folder created successfully
Common Pitfalls
Common mistakes include:
- Not using
{ recursive: true }when creating nested folders, causing errors if parent folders don't exist. - Using the callback version without handling errors properly.
- Calling
fs.mkdiroutside an async function without handling the returned promise.
Always handle errors to avoid crashes.
javascript
import { mkdir } from 'fs/promises'; // Wrong: missing recursive option for nested folders // await mkdir('./parent/child'); // This throws if 'parent' doesn't exist // Right: use recursive to create all needed folders await mkdir('./parent/child', { recursive: true });
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| path | String path of the directory to create | './data' |
| options | Object with options, e.g., recursive | { recursive: true } |
| Returns | Promise that resolves when done | Promise |
Key Takeaways
Use fs.mkdir from fs/promises with async/await for modern directory creation.
Add { recursive: true } option to create nested directories safely.
Always handle errors to prevent your program from crashing.
fs.mkdir returns a promise, so use await or .then() to manage it.
Avoid using the callback version unless you handle errors properly.