Working with Directories
A directory is a folder on the disk. The fs module can make folders and list them.
Making a folder and checking it
This makes mydir and checks that it exists.
const fs = require("fs");
fs.mkdirSync("mydir", { recursive: true });
console.log(fs.existsSync("mydir"));Making a folder
This makes a folder named photos.
fs.mkdirSync("photos", { recursive: true });
console.log("Folder made");Listing a folder
This makes a folder with two files. The print lists both names.
fs.mkdirSync("listdir", { recursive: true });
fs.writeFileSync("listdir/a.txt", "A");
fs.writeFileSync("listdir/b.txt", "B");
console.log(fs.readdirSync("listdir"));Example
const fs = require("fs");
fs.mkdirSync("mydir", { recursive: true });
fs.writeFileSync("mydir/note.txt", "A note");
console.log(fs.readdirSync("mydir"));Key points
- mkdirSync makes a new folder.
- mkdir is short for make directory.
- The input { recursive: true } lets mkdirSync make missing parent folders too.
- readdirSync lists the names inside a folder.
- readdir is short for read directory.
- readdirSync gives back the names as an array.
- existsSync checks whether a file or folder exists.
- existsSync gives back true or false.
In this example, mkdirSync makes a folder named mydir. The program writes a file named note.txt inside it. The print lists the names inside mydir. The list holds one name.
Note
mkdirSync without recursive fails when a parent folder is missing.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which method lists the names inside a folder?