← Back to Node.js Course | Chapter 5: File System | Lesson 5 of 7

Directory operations

Directories can be created, listed and inspected with fs.

In this page:

  1. Directory operations
Syntax
javascript
fs.mkdir('directory', { recursive: true }, (err) => {});
fs.readdir('directory', (err, names) => {});
fs.readdir('directory', { withFileTypes: true }, (err, entries) => {});

Directory operations

mkdir creates folders (recursive makes parents), readdir lists names, and withFileTypes tells files from folders. stat reveals size and type. Combining these builds tools like recursive directory walkers.

Note: Use readdir with withFileTypes to avoid an extra stat per entry.

Example: Directory operations

javascript
const fs = require("fs");
fs.mkdirSync("proj/src", { recursive: true });
fs.writeFileSync("proj/readme.md", "# hi");
fs.writeFileSync("proj/src/app.js", "1");
const entries = fs.readdirSync("proj", { withFileTypes: true });
console.log(entries.map((e) => e.name + (e.isDirectory() ? "/" : "")).sort());

// Output:
// [ 'readme.md', 'src/' ]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Forgetting recursive for nested folders
  2. Assuming readdir returns full paths
  3. Not handling EEXIST
Chapter Summary
  • mkdir creates folders
  • readdir lists names
  • withFileTypes identifies entries
  • stat gives details
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.