Malekbenz

Hi, I'm MalekBenz. I author this blog, I'm FullStack Developer, create courses & love learning, writing, teaching technology. ( Javascript, C#, ASP.NET , NodeJS, SQL Server )

Serving static content with ExpressJs

What we are going to do today is Serving a static content without using Apache, nginx or IIS. What we need is creating Http server with expressjs. This post goes into how this can be achieved.

if you don’t have node js already installed you can Install & run your first application Nodejs.

Install express

Express is a nodejs framework that has great built in capabilities to serve static content.

Create a webserver directory to hold your application, and make that your working directory and then create www

    $ mkdir  webserver
    $ cd webserver
    $ mkdir www

create a file ‘app.js’

CMD

Now install Express in the webserver directory and save it in the dependencies list. For example:

    $  npm install express

CMD

Let’s type some code

add the following code to app.js file, We use Visual studio code to edit the file:

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

    app.use(express.static(__dirname + '/www'));

    app.listen(3000);

vs code

add index.html file to www folder:

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Document</title>
            <link href='/style.css' rel='stylesheet' type='text/css'>
        </head>
        <body>
            <h1> Serving static contents with expressjs app </h1>
            <img src="/image.jpg" alt="image">
        </body>
        </html>

vs code

Add style.css file to www folder:

    h1 {
        background-color: rosybrown
    }

vs code

then Add an image to www folder and name it image.jpg

vs code

Run the application

Run the application:

    $ node app.js

loadl application

The application starts a server and listens on port 3000 for connections. The app responds with “Welcome to express api” for requests to the root URL (/) or route.

load http://localhost:3000/ in a browser to see the output.

vs code

Alow contents to be cached

Now our http server is working, let’s add some functionalities like caching :

Modify you app.js file :

    app.use(express.static(__dirname + '/www', { maxAge: 3600000 }));

vs code

max-age property of the Cache-Control header is in milliseconds (3600000 =1 hour)

Save the file and run th application again

To stop the app Ctrl + C

vs code

Any files under the www folder will be server

**This is your static content web server working **

Comments