A Complete Guide - Expressjs Serving Static Files and Templating ejs pug
Explaining Express.js for Serving Static Files and Templating with EJS & Pug
Serving Static Files in Express.js
Static files include resources like HTML, CSS, JavaScript, images, and any other files that do not require server-side processing. Serving static files efficiently is crucial for performance and user experience.
Setting Up Static File Serving
To serve static files in Express.js, you need to use the express.static middleware. Here’s a step-by-step guide:
Install Express.js: If you haven't installed Express.js yet, do so using npm (Node Package Manager):
npm install expressCreate a Server: Set up a basic Express.js server and specify which folder holds your static files.
const express = require('express'); const app = express(); // Specify the directory for static files app.use(express.static('public')); // Start the server on port 3000 app.listen(3000, () => { console.log('Server running on });Organize Static Files: Add your static files to the directory specified in
express.static, e.g.,publicin the example above. For instance, place your CSS, JavaScript, and images inside thepublicfolder.public/styles.csspublic/scripts.jspublic/images/logo.png
Accessing Static Files: You can access these files directly via the URL. For example, to access
styles.css, go to
Customizing Static File Serving
Express.js also allows you to serve multiple directories and modify how these files are cached. For instance, to serve files from additional directories, use app.use multiple times:
// Serve files from 'public' and 'assets' directory
app.use(express.static('public'));
app.use(express.static('assets'));
For better control over caching, you can pass options to express.static. For example:
app.use(express.static('public', {
maxAge: '1d' // Cache static files for one day
}));
Templating with EJS (Embedded JavaScript)
EJS allows you to generate HTML output by combining HTML and JavaScript. This templating engine enables you to dynamically create markup with the help of JavaScript variables, loops, and conditional statements.
Setting Up EJS
Install EJS: Add EJS to your project via npm.
npm install ejsConfigure EJS in Express: Tell Express.js to use EJS as its templating engine.
app.set('view engine', 'ejs'); app.set('views', './views'); // This is the default, you can specify a different folderCreate EJS Templates: Develop your HTML templates in the
viewsfolder. Use EJS syntax to embed JavaScript.Here's a simple example (
views/index.ejs):<!DOCTYPE html> <html> <head> <title>My Page</title> </head> <body> <h1>Welcome, <%= user %>!</h1> <ul> <% users.forEach(function(user) { %> <li><%= user %></li> <% }); %> </ul> </body> </html>Render EJS Templates: Use the
res.rendermethod to serve EJS templates.app.get('/', (req, res) => { const user = 'Alice'; const users = ['Bob', 'Charlie']; res.render('index', { user, users }); });
When a request is made to the root URL, Express.js will render index.ejs and pass it the user and users variables.
Templating with Pug (Formerly Jade)
Pug is another templating engine for Express.js that features a clean, elegant syntax. Pug templates use indentation to denote HTML structure, resulting in leaner, more readable code.
Setting Up Pug
Install Pug: Add Pug to your project via npm.
npm install pugConfigure Pug in Express: Tell Express.js to use Pug as its templating engine.
app.set('view engine', 'pug'); app.set('views', './views'); // This is the default, you can specify a different folderCreate Pug Templates: Develop your HTML templates in the
viewsfolder. Use Pug syntax to embed JavaScript.Here's a simple Pug template example (
views/index.pug):doctype html html head title My Page body h1 Welcome, #{user}! ul each person in users li= personRender Pug Templates: Use the
res.rendermethod to serve Pug templates, similar to how it's done for EJS.app.get('/', (req, res) => { const user = 'Alice'; const users = ['Bob', 'Charlie']; res.render('index', { user, users }); });
Pug's syntax eliminates the need for tags to close, making templates more concise and easier to maintain.
Conclusion
Online Code run
Step-by-Step Guide: How to Implement Expressjs Serving Static Files and Templating ejs pug
1. Setting up an Express.js Application
First, let's create a new folder for your project and initialize it with npm.
mkdir express-static-templating
cd express-static-templating
npm init -y
Next, install Express.js:
npm install express
2. Serving Static Files
Create a file called index.js in the root of your project. We'll use this to set up our basic Express application.
const express = require('express');
const app = express();
const port = 3000;
// Serve static files from the "public" directory
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
app.listen(port, () => {
console.log(`Server is running on
});
Create a directory named public and add an index.html file inside it.
<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Static Files</title>
</head>
<body>
<h1>Hello from static files!</h1>
<img src="assets/image.png" alt="Sample Image">
</body>
</html>
Add any image, say image.png, inside a folder named assets inside your public directory.
Now run your application:
node index.js
Visit You should see your index.html file with the static image.
3. Templating with EJS
To use EJS for templating, first install EJS:
npm install ejs
Edit your index.js file to use EJS:
const express = require('express');
const app = express();
const port = 3000;
// Set EJS as the templating engine
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index', { title: 'EJS Templating', message: 'Hello from EJS!' });
});
app.listen(port, () => {
console.log(`Server is running on
});
Create a views directory at the root of your project. Inside views, create an index.ejs file:
<!-- views/index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
</head>
<body>
<h1><%= message %></h1>
<img src="/assets/image.png" alt="Sample Image">
</body>
</html>
Run your application again:
node index.js
Visit You should see your index.ejs file rendered with dynamic content.
4. Templating with Pug
To use Pug for templating, first install Pug:
npm install pug
Edit your index.js file to use Pug:
const express = require('express');
const app = express();
const port = 3000;
// Set Pug as the templating engine
app.set('view engine', 'pug');
app.get('/', (req, res) => {
res.render('index', { title: 'Pug Templating', message: 'Hello from Pug!' });
});
app.listen(port, () => {
console.log(`Server is running on
});
Inside your views directory, create an index.pug file:
// views/index.pug
doctype html
html(lang='en')
head
meta(charset='UTF-8')
meta(name='viewport', content='width=device-width, initial-scale=1.0')
title= title
body
h1= message
img(src='/assets/image.png', alt='Sample Image')
Run your application again:
node index.js
Visit You should see your index.pug file rendered with dynamic content.
Summary
- Serving Static Files: Use
app.use(express.static('public'))to serve static files from a directory namedpublic. - Templating with EJS: Set
app.set('view engine', 'ejs')and use.ejsfiles in aviewsdirectory to render HTML with dynamic content. - Templating with Pug: Set
app.set('view engine', 'pug')and use.pugfiles in aviewsdirectory to render HTML with dynamic content.
Top 10 Interview Questions & Answers on Expressjs Serving Static Files and Templating ejs pug
Top 10 Questions and Answers on Express.js Serving Static Files and Templating with EJS and Pug
1. How do I serve static files in Express.js?
app.use(express.static('public'));
Now, any files in the public directory can be accessed directly by the URL path. For example, for an image named logo.png located in public/images.
2. What is EJS (Embedded JavaScript) in Express.js and how do I set it up?
Answer: EJS is a simple templating engine that lets you generate HTML markup using JavaScript. It supports server-side rendering and is very easy to integrate with Express.js. To set up EJS, install it first:
npm install ejs
Then, set EJS as the templating engine in your Express app configuration:
app.set('view engine', 'ejs');
Create an views folder and put your .ejs files there. To render an index.ejs file, use:
app.get('/', (req, res) => {
res.render('index', { title: 'Home Page' });
});
Here, the title is a variable passed to the index.ejs template.
3. How can I use Pug templating engine with Express.js?
Answer: Pug (formerly Jade) is a robust, high-performance templating engine for Node.js. It makes writing HTML cleaner and more maintainable by allowing the use of clean syntax, partials, and inheritance. To use Pug in your Express.js application, first install it:
npm install pug
Next, set it as your templating engine:
app.set('view engine', 'pug');
Create a views directory and place your .pug files within it. Then render them in your route handlers:
app.get('/', (req, res) => {
res.render('index', { title: 'Welcome' });
});
In the index.pug file, you can utilize Pug's syntax to dynamically generate HTML.
4. How do I include a partial in both EJS and Pug?
Answer: Including partials in both EJS and Pug helps manage code duplication and improves organization.
For EJS:
Create a partial file, e.g., header.ejs in the views/partials folder. To include this partial in another file, use:
<%- include('partials/header') %>
For Pug:
In Pug, you can include partials in a similar way. For example, create a file named header.pug and include it as follows:
include header
Make sure all partials are in the views folder or specify a different path if necessary.
5. How do I pass variables to templates in both EJS and Pug?
Answer: Passing variables to templates in EJS or Pug allows you to dynamically generate content based on server-side data.
For EJS:
You can pass variables directly as the second argument to res.render:
app.get('/', (req, res) => {
res.render('index', { title: 'Home', message: 'Welcome to my site!' });
});
In index.ejs, you can access these variables using <%= %>:
<title><%= title %></title>
<p><%= message %></p>
For Pug:
The approach is similar. Pass variables in the render method:
app.get('/', (req, res) => {
res.render('index', { title: 'Home', message: 'Welcome to my site!' });
});
Then access them using Pug syntax in index.pug:
title= title
p= message
6. How do I use conditional logic in EJS and Pug?
Answer: Conditional logic helps to manage the rendering of content based on certain conditions.
For EJS:
In EJS, you can use traditional JavaScript if-else statements wrapped in <% %> blocks:
<% if (user) { %>
<h1>Hello, <%= user.name %></h1>
<% } else { %>
<h1>Please log in</h1>
<% } %>
For Pug: Pug also supports conditional logic with a more concise syntax:
if user
h1 Hello,= user.name
else
h1 Please log in
7. Can I use loops in EJS and Pug?
Answer: Yes, you can iterate over arrays using loops in both EJS and Pug to dynamically render content.
For EJS:
Use a for loop or forEach method:
<ul>
<% items.forEach((item) => { %>
<li><%= item %></li>
<% }) %>
</ul>
For Pug:
Pug simplifies this with a each loop:
ul
each item in items
li= item
8. How can I include multiple static folders in Express?
Answer: You can serve files from multiple directories by calling express.static multiple times with different paths:
app.use(express.static('public'));
app.use(express.static('another'));
With this configuration, Express.js will look first in the public directory and then in the another directory for requested files.
9. What is the difference between EJS and Pug?
Answer: While both EJS and Pug are templating engines for Express.js, they have different philosophies.
- EJS (Embedded JavaScript): EJS is an embedded JavaScript templating engine which lets you generate HTML markup with plain JavaScript. Its syntax is HTML-centric and allows you to write HTML directly with embedded JavaScript inside
<% %>tags. - Pug (formerly Jade): Pug is a more compact templating engine with a clean and minimalistic syntax. It uses indentation and whitespace instead of tags and closing tags. The code looks more like CSS and is often simpler and more readable for templating purposes.
10. How do I handle errors in rendering templates with EJS or Pug in Express?
Answer: To handle errors during the rendering process, you can use a try-catch block around the res.render call or pass an error-handling middleware function.
Basic Error Handling with try-catch:
app.get('/', async (req, res) => {
try {
const data = await someAsyncDataFetch();
res.render('index', data);
} catch (err) {
res.status(500).send('Server Error');
}
});
Error Handling Middleware: You can create an error-handling middleware to catch all errors:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Make sure to place this middleware after all other route handlers and middleware.
Login to post a comment.