Why does “Cannot find module ‘ejs'” occur?

Below, are the reasons for “Cannot find module ‘ejs'” occurring:

  • Module Not Installed
  • Incorrect Module Name

Reason 1: Module Not Installed

In this scenario, Node.js script uses the ‘ejs’ module to read an EJS template from ‘index.ejs’, compiles it, replaces a variable with the value ‘World’, generates HTML, and writes it to ‘output.html’. But, as the module is not installed, it will give the Error as “Cannot find module ‘ejs'”. Without installing the module, we cannot use ejs.

Javascript




const ejs = require('ejs');
const fs = require('fs');
const template = fs.readFileSync('index.ejs', 'utf-8');
const compiledTemplate = ejs.compile(template);
const data = { name: 'World' };
const renderedHTML = compiledTemplate(data);
fs.writeFileSync('output.html', renderedHTML);
console.log('HTML file generated successfully!');


Output:

node:internal/modules/cjs/loader:998
throw err;
^

Error: Cannot find module 'ejs'

Reason 2: Incorrect Module Name

Another reason for the error mighr be a typing mistake or incorrect naming when trying to import the ejs module. Node.js is case-sensitive, so ensure that the module name is spelled correctly.

Javascript




const ejs = require('EJS'); // Incorrect


Output:

node:internal/modules/cjs/loader:998
throw err;
^

Error: Cannot find module 'EJS'

Below are the solutions for “Cannot find module ‘ejs'” Error:

How to Resolve Error: Cannot find module ‘ejs’ ?

EJS (Embedded JavaScript) is the templating engine for JS that simplifies the task of generation of HTML markup with embedded JS code. It allows you to embed dynamic content and logic directly within the HTML templates, which makes it easier to generate dynamic web pages in Node.js Apps. While working with this engine, developers usually face the Cannot find module ‘ejs‘ error. In this article, we will learn how to fix or resolve this error.

Similar Reads

What is the “Cannot find module ‘ejs'” Error?

The Cannot find module ‘ejs‘ error occurs when the Node.js application cannot locate the required ejs module in the application. Some possibilities and occurrence scenarios encounter this error while trying to use ejs module. This error suggests that this module is not installed or it may be named differently. It is important to verify the correct installation of the required module and also ensure that the module’s name matches correctly....

Why does “Cannot find module ‘ejs'” occur?

Below, are the reasons for “Cannot find module ‘ejs'” occurring:...

Approach 1: Install ejs Module

...

Approach 2: Correct the Spelling Mistake

...