Interview Q&A / Node.js
Node.js interview questions
The event loop on the server, streams, modules and building APIs with Express.
Prefer rapid revision? Practise Node.js short interview answers →
- How do you check whether a file exists in Node.js?
Use fs.promises.access in a try/catch, or fs.existsSync for quick sync checks. Better still, skip the check and handle the ENOENT error when you open the file, because the file can change between check and use.
BeginnerQuick answer1 min read - How do you list all files in a folder and its subfolders in Node.js?
Use fs.promises.readdir with the recursive option on recent Node versions, or write a small recursive function using withFileTypes to tell files from directories.
BeginnerQuick answer1 min read - What is the difference between fs.readFileSync, fs.readFile and fs.promises.readFile?
readFileSync blocks the thread until done. readFile takes a callback and does not block. fs.promises.readFile returns a promise for use with await. In servers, prefer the non-blocking forms.
BeginnerQuick answer1 min read - Why use path.join instead of joining file paths with plus signs?
path.join uses the correct separator for the operating system, normalises extra slashes and dot segments, and avoids missing or doubled slashes, so paths work on Windows, Linux and macOS.
BeginnerQuick answer1 min read - How do you read a very large file line by line in Node.js?
Create a read stream and pass it to readline.createInterface, then loop with for await. Only a small chunk sits in memory at a time, unlike readFile, which loads the whole file.
IntermediateQuick answer1 min read - How do you write a JSON file in Node.js without risking a half-written file?
Write the data to a temporary file in the same folder, then rename it over the target. Rename is atomic on the same filesystem, so readers see either the old file or the complete new one.
IntermediateQuick answer1 min read