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. What does the main field in package.json do?

    main names the entry file that Node loads when someone requires or imports your package by name. If it is missing, Node falls back to index.js. Modern packages may also use the exports field.

    BeginnerQuick answer1 min read
  4. What happens when you require the same module twice in Node.js?

    The file runs only once. Node caches the exported object in require.cache, so later require calls return the same object, which means shared state between files.

    BeginnerQuick answer1 min read
  5. What is the difference between module.exports and exports in CommonJS?

    exports is just a shortcut variable pointing at module.exports. You can add properties to either, but only module.exports is what require returns, so reassigning exports alone exports nothing.

    BeginnerQuick answer1 min read