Expressjs Serving Static Files And Templating Ejs Pug Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of 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:

  1. Install Express.js: If you haven't installed Express.js yet, do so using npm (Node Package Manager):

    npm install express
    
  2. Create 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 http://localhost:3000');
    });
    
  3. Organize Static Files: Add your static files to the directory specified in express.static, e.g., public in the example above. For instance, place your CSS, JavaScript, and images inside the public folder.

    • public/styles.css
    • public/scripts.js
    • public/images/logo.png
  4. Accessing Static Files: You can access these files directly via the URL. For example, to access styles.css, go to http://localhost:3000/styles.css.

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
  1. Install EJS: Add EJS to your project via npm.

    npm install ejs
    
  2. Configure 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 folder
    
  3. Create EJS Templates: Develop your HTML templates in the views folder. 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>
    
  4. Render EJS Templates: Use the res.render method 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
  1. Install Pug: Add Pug to your project via npm.

    npm install pug
    
  2. Configure 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 folder
    
  3. Create Pug Templates: Develop your HTML templates in the views folder. 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= person
    
  4. Render Pug Templates: Use the res.render method 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

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

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 http://localhost:${port}`);
});

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 http://localhost:3000. 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 http://localhost:${port}`);
});

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 http://localhost:3000. 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 http://localhost:${port}`);
});

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 http://localhost:3000. 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 named public.
  • Templating with EJS: Set app.set('view engine', 'ejs') and use .ejs files in a views directory to render HTML with dynamic content.
  • Templating with Pug: Set app.set('view engine', 'pug') and use .pug files in a views directory 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, http://localhost:3000/images/logo.png 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.

You May Like This Related .NET Topic

Login to post a comment.