Static Files in Express Js

  • In Express.js, static files are files (such as images, stylesheets, scripts, etc.) that are served directly to clients without any processing by the server. These files typically do not change dynamically based on user input or application logic and are instead served as-is. Express provides a built-in middleware called `express.static` to serve static files efficiently.
Let's explore the concept of serving static files in Express.js in more detail:
  • Static Middleware Setup: To serve static files in Express.js, you use the `express.static` middleware. This middleware takes a directory path as an argument, and any files within that directory become accessible to clients.

    const express = require('express');
    const app = express();

    // Serve static files from the 'public' directory
    app.use(express.static('public'));

    // Other routes and middleware can go here

    const PORT = 3000;
    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });

  • In this example, the `public` directory contains the static files, and `express.static('public')` is used to serve them. Now, any file inside the `public` directory can be accessed directly by clients.
  • Static File Paths: When you use the `express.static` middleware, the file paths are relative to the directory you specify. For example, if you have a file named `styles.css` inside the `public/css` directory, clients can access it at `http://localhost:3000/css/styles.css`.
  • Using Multiple Directories: You can use `express.static` multiple times to serve files from different directories:

    app.use(express.static('public'));
    app.use(express.static('images'));

  • This way, both the `public` and `images` directories are available to clients.
  • Customizing the Path Prefix: You can specify a path prefix for the static files by providing it as the first argument to `express.static`. For example:

    app.use('/static', express.static('public'));

  • Now, files from the `public` directory can be accessed at `http://localhost:3000/static/file-name`.
  • Caching: Express.js automatically adds caching headers to static files, which can improve performance by instructing clients to cache files locally for a certain period. This behavior can be controlled using the `maxAge` option.

    app.use('/static', express.static('public', { maxAge: 86400000 }));

  • In this example, the `maxAge` option is set to one day (in milliseconds).
  • Security Considerations: Be cautious when serving static files, as it might expose sensitive information. Avoid serving directories containing critical files or data.
  • Middleware Order: The order of middleware matters in Express.js. Make sure to place the `express.static` middleware before other routes or middleware that might interfere with static file serving.
  • Using a Virtual Path Prefix: You can use a virtual path prefix to make static files appear as if they are coming from a different path:

    app.use('/static', express.static('public'));

  • Now, files in the `public` directory can be accessed at `http://localhost:3000/static/file-name`.
Summary:
  • Serving static files in Express.js is a fundamental aspect of web application development. The `express.static` middleware simplifies the process by efficiently serving files directly to clients. This is particularly useful for serving stylesheets, images, scripts, and other resources required by your web application.
Let's create a complete example where we use CSS, images, and JavaScript as static content in an EJS template.
  • Project Structure: Create a project structure with the following directories and files:

    - my-express-app/
        - public/
            - css/
                - styles.css
            - images/
                - logo.png
            - js/
                - script.js
        - views/
            - index.ejs
        - app.js
        - package.json

  • CSS, Images, and JavaScript Files: Create some sample CSS, image, and JavaScript files:

    /* public/css/styles.css */

    body {
        font-family: 'Arial', sans-serif;
        background-color: #f0f0f0;
        text-align: center;
    }

    h1 {
        color: #333;
    }

    img {
        max-width: 100%;
    }

  • Place any image file (e.g., `logo.png`) in the `public/images/` directory.

    // public/js/script.js

    document.addEventListener('DOMContentLoaded', function () {
        console.log('Script loaded!');
    });

  • EJS Template: Create an EJS template (`index.ejs`) in the `views` directory:

    <!-- views/index.ejs -->

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="/css/styles.css">
        <title>Express.js Static Content Example</title>
    </head>

    <body>

        <h1>Welcome to Express.js Static Content Example</h1>
        <img src="/images/logo.png" alt="Logo">
        <script src="/js/script.js"></script>

    </body>

    </html>

  • In this template, we reference the CSS file, image, and JavaScript file using their relative paths in the `public` directory.
  • Express App (app.js): Now, let's set up the Express.js application (`app.js`):

    // app.js

    const express = require('express');
    const app = express();
    const path = require('path');

    // Set EJS as the view engine
    app.set('view engine', 'ejs');

    // Serve static files from the 'public' directory
    app.use(express.static(path.join(__dirname, 'public')));

    // Define a route to render the index view
    app.get('/', (req, res) => {
        // Render the 'index' view
        res.render('index');
    });

    const PORT = 3000;
    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });

  • Run the Application: Run your application using the command:

    node app.js

  • Visit `http://localhost:3000` in your browser, and you should see the rendered EJS template with the applied styles, image, and JavaScript.
  • This example demonstrates how to use CSS, images, and JavaScript as static content in an EJS template in an Express.js application. The `express.static` middleware is used to serve these static files, and they are referenced in the EJS template using their relative paths.

No comments:

Post a Comment