Node.js - Error: Cannot find module '<module name>'

Cover Image for Node.js - Error: Cannot find module '<module name>'

In this article you will understand more about nodejs error: cannot find module <module-name>

We've all encountered at some point the following issue:

  throw err;
Error: Cannot find module 'esm'
Require stack:
- internal/preload
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at Module._preloadModules (internal/modules/cjs/loader.js:1217:12)
    at loadPreloadModules (internal/bootstrap/pre_execution.js:449:5)
    at prepareMainThreadExecution (internal/bootstrap/pre_execution.js:76:3)
    at internal/main/run_main_module.js:7:1 {
  requireStack: [ 'internal/preload' ]

In my case, it was esm module because what I was trying to do is to run a file that contains ES syntax (like import / export etc).

node -r esm index.js

The -r flag means that before running the actual script, load a certain package, in this case, esm.

If Node cannot find that package it will throw the error I've previously mentioned.

Possible fixes

  1. Check if that module is installed (maybe is not listed in project dependencies). If not, install it npm i <module-name> (eg. npm i esm)
  1. Check if any module is installed (maybe you forgot to run npm install and install all the dependencies). Search for the node_modules folder inside of your project. If you can't find any node_modules folder it means that no packages (modules) are installed, so you can only use the Node internal packages (like fs module)

Daniel Turuș


Hi! My name is Daniel and I am a Full-stack JavaScript developer.

If you like my material, please consider following me on Twitter to get notified when new posts are published, ask me a question and stay in touch.