Interview Q&A / Node.js

INTERVIEW Q&A · 68 QUESTIONS

Node.js interview questions

The event loop on the server, streams, modules and building APIs with Express.

  1. What is the difference between CommonJS (require) and ES modules (import) in Node.js?

    CommonJS uses require and module.exports, loads files synchronously, and was Node's original system. ES modules use import and export, are the JavaScript standard, are analysed before running, and support top-level await. Node supports both.

    BeginnerIn-depth3 min read
  2. How do you get __dirname and __filename inside an ES module?

    They do not exist in ES modules. Use import.meta.url with fileURLToPath and path.dirname, or on recent Node versions import.meta.dirname and import.meta.filename.

    BeginnerQuick answer1 min read
  3. How do you tell Node.js to treat your files as ES modules?

    Set "type": "module" in package.json so .js files are ESM, or use the .mjs extension for individual files. Use .cjs to force CommonJS inside an ESM project.

    BeginnerQuick answer1 min read
  4. How can CommonJS code load an ES module?

    Use dynamic import(), which works in CommonJS and returns a promise. Plain require of an ES module was not allowed historically; newer Node versions added limited support, so dynamic import is the safe choice.

    IntermediateQuick answer1 min read
  5. What is top-level await and where can you use it in Node.js?

    It lets you use await directly at the top of a file without wrapping it in an async function. It works only in ES modules, and it delays anything that imports that module until the promise settles.

    IntermediateQuick answer1 min read