Loading

Quipoin Menu

Learn • Practice • Grow

node-js / Working with Directories
interview

Q1. How do you create a directory in Node.js?
Use fs.mkdir() to create directories. Example:
fs.mkdir('newdir', (err) => { if (err && err.code !== 'EEXIST') throw err; });
For creating nested directories, use { recursive: true } option:
fs.mkdir('parent/child', { recursive: true }, callback);
. The sync version is fs.mkdirSync().

Q2. How do you read the contents of a directory?
Use fs.readdir() to get an array of filenames. Example:
fs.readdir('./folder', (err, files) => { files.forEach(file => console.log(file)); });
With { withFileTypes: true } option, you get fs.Dirent objects that allow checking if each entry is a file or directory via .isFile() and .isDirectory().

Q3. How do you remove a directory?
Use fs.rmdir() to remove an empty directory. Example:
fs.rmdir('emptydir', (err) => { ... });
For non-empty directories, use fs.rm() with { recursive: true, force: true } (Node.js 14+). Example:
fs.rm('folder', { recursive: true, force: true }, callback);
. Be careful with recursive deletion.

Q4. How do you check if a path is a directory?
Use fs.stat() which returns a Stats object with .isDirectory() method. Example:
fs.stat('somepath', (err, stats) => { if (err) throw err; if (stats.isDirectory()) console.log('It is a directory'); });
For async/await, use fs.promises.stat(). This works for both files and directories.

Q5. How do you rename or move a directory?
Use fs.rename() to rename or move a directory. Example:
fs.rename('oldname', 'newname', (err) => { ... });
This works for both files and directories. The operation is atomic; if an error occurs, the original path remains unchanged. For cross-device moves, you might need to copy and delete.