Fixing Express Error: TypeError: this.engine is not a function

In express.js you can get this error:

TypeError: this.engine is not a function

Typically this is caused by copy-pasting incomplete code from the internet.

To fix it, you need to install a template engine and register it with Node. You also need to ensure your template files have the correct extension.

For example, EJS is popular, and has HTML-like templates:

    <% for(var i=0; i
  • <%= supplies[i] %>
  • <% } %>

To make this available, install it from NPM:

$ npm install --save ejs
npm WARN package.json image-annotation@1.0.0 No repository field.
npm WARN package.json image-annotation@1.0.0 No README data
ejs@2.4.1 node_modules\ejs

Then register it with express (the first argument is a magic string, and the second argument is how it will ‘require’ it)

app.set('view engine', 'ejs');  

Then, make sure you have “.ejs” as the file extension (it’s not clear why this is necessary, since ‘view engine’ seems to be a single value):

res.render('search.ejs', output);

You can also require ejs yourself and call it directly, using the instructions in the documentation:

let ejs = require('ejs');

var template = ejs.compile(str, options);
template(data);
// => Rendered HTML string 
 
ejs.render(str, data, options);

Leave a Reply

Your email address will not be published. Required fields are marked *