Search code examples
node.jsexpressejs

How to solve Error : cannot find module "ejs"?


I started a new (and first) express.js project using ejs but facing to this following error while accessing to the page :

Error: Cannot find module 'ejs '
Require stack:
- C:\wamp64\www\myproject\node_modules\express\lib\view.js
- C:\wamp64\www\myproject\node_modules\express\lib\application.js
- C:\wamp64\www\myproject\node_modules\express\lib\express.js
- C:\wamp64\www\myproject\node_modules\express\index.js
- C:\wamp64\www\myproject\server.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:925:15)
    at Function.Module._load (node:internal/modules/cjs/loader:769:27)
    at Module.require (node:internal/modules/cjs/loader:997:19)
    at require (node:internal/modules/cjs/helpers:92:18)
    at new View (C:\wamp64\www\myproject\node_modules\express\lib\view.js:81:14)
    at Function.render (C:\wamp64\www\myproject\node_modules\express\lib\application.js:570:12)
    at ServerResponse.render (C:\wamp64\www\myproject\node_modules\express\lib\response.js:1012:7)
    at C:\wamp64\www\myproject\server.js:10:13
    at Layer.handle [as handle_request] (C:\wamp64\www\myproject\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\wamp64\www\myproject\node_modules\express\lib\router\route.js:137:13) 

Here is how I proceed from the beginning :

  1. Created a new folder called myproject
  2. Created a new file called server.js
  3. node init
  4. Modified package.json to add nodemon
  5. npm install --save nodemon
  6. npm install --save express
  7. npm install --save ejs

My file server.js :

var app = require('express')();
app.set('view engine', 'ejs');

app.get('/', function (req, res) {
    res.setHeader('Content-Type', 'text/plain');
    res.send('Accueil');
})
    .get('/album', function(req, res){
        res.setHeader('Content-Type', 'text/plain');
        res.render('album.ejs ', {name :'yop'});
    })
    .use(function(req, res, next){
        res.setHeader('Content-Type', 'text/plain');
        res.status(404).send('Page introuvable !');
    });

app.listen(8080);

My file package.json :

{
  "name": "myproject",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^3.1.5",
    "express": "^4.17.1",
    "nodemon": "^2.0.6"
  }
}

My project's structure :

My project directory
   node_modules folder
   views folder
      album.ejs file
   package.json
   server.js


Solution

  • You add one extra space accidentally behind the ejs.

    res.render('album.ejs ', {name :'yop'});
    

    Remove that space like below.

    res.render('album.ejs', {name :'yop'});
    

    And you could just use the file name without extension name.

    res.render('album', {name :'yop'});