Explain Codes LogoExplain Codes Logo

Using HTML in Express instead of Jade

html
web-development
express
template-engine
Anton ShumikhinbyAnton Shumikhin·Dec 25, 2024
TLDR

To opt for pure HTML in Express instead of Pug (formerly Jade), you can leverage EJS's functionality which renders HTML.

npm install ejs

Harness this in your Express setup code:

const express = require('express'); const app = express(); // Tell Express to consider '.html' as special. EJS is our secret weapon app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); // Time to serve up some HTML magic! ♪┏(°.°)┛┗(°.°)┓♪ app.get('/', (req, res) => res.render('index')); app.listen(3000);

Drop your index.html in the views folder, and like magic, Express will serve it without needing .html in res.render().

Serve individual HTML files in Express

Sometimes, simplicity is key. You might prefer to serve individual HTML files in Express without a template engine, like a 5-year-old serving pretend tea ☕️. In that case, Express's res.sendFile is your best friend.

const path = require('path'); app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'views/index.html')); });

Just make sure to set the Content-Type properly and give error handling some love ❤️:

const options = { dotfiles: 'ignore', headers: { 'x-timestamp': Date.now(), 'x-sent': true, 'Content-Type': 'text/html' } }; app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'views/index.html'), options, (err) => { if (err) { console.log(err); res.status(err.status).end(); } }); });

Roll your own custom engine

Want to play DIY? Create your custom template engine to serve HTML files using app.engine and fs.readFile. This option is lighter than EJS or other template engines. Creates less fluff than a double-coated retriever shedding its winter coat 🐕.

const fs = require('fs'); app.engine('html', (filePath, options, callback) => { fs.readFile(filePath, (err, content) => { if (err) return callback(err); // This is an ultra-basic template engine const rendered = content.toString().replace('#title#', options.title || ''); return callback(null, rendered); }); }); app.set('view engine', 'html'); app.set('views', './views'); // Note this: views directory

Remember to sprinkle some love on caching strategies, whether you're using in-memory strategies or a clever custom implementation to squeeze out that extra performance.

Strategies for caching

Caching views becomes necessary as your application scales. It is like vegetables to your dinner, not the star but crucial. Express allows for caching configurations—set view cache to true in the production environment:

app.set('view cache', true);

When serving files directly with res.sendFile, patient handling of both client and server-side caching can reduce strain on your server. Remember, effective caching can make your app as swift as a cheetah chasing lunch 🐆.

Multifaceted file extensions and rendering

Express's app.engine provides mapping functionalities for different file extensions for flexible rendering options—it's like a Swiss Army knife for file rendering 🔪.

app.engine('md', someMarkdownEngine());

Use this approach to render Markdown files or any other file types that suit your fancy.

Keep pace with Express and Node.js versions

Regularly consult the official Express API reference and Node.js documentation to stay updated with the latest practices and avoid deprecated methods. Time and tide wait for no man, nor does Express!