Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

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
http://localhost:3000/images/photo1.png

var express = require('express');
var app = express();
app.use(express.static('app/public'));

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(express.static(filePath));

app.use(function(req, res){
    console.log("Request IP", + req.url);
    console.log("Request data: " + new Date());
    
    res.status(404);
    res.send("File not found");
});
Serving static file in Express

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top