Serving static file in Express

We can use Express’s built-in middleware called static to serve static file like images, CSS files, and JavaScript file to the client. First, we have to define the directory where will put all are the static file to the middleware function express.static to start serving the files directly. We will define public as a directory for serving the static file. We can reach our static file in the browser as example

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

Here we don’t have to require the path module, as we are run the node app in the same folder as the path. If we are put the static directory in another folder, then it is safer to use an absolute path of the directory that you want to serve. Then we will change our code as

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

var filePath = path.join(__dirname, "public");

app.use(function(req, res){
    console.log("Request IP", + req.url);
    console.log("Request data: " + new Date());
    res.send("File not found");
Spread the love

Leave a Comment

Your email address will not be published.

Scroll to Top