Specify Static Folder in Express JS

Static folder is used for keeping all the static files like css files, images etc. In express JS we mention the static folder in the code. So the server can find all the static contents of the app in that folder. Then it can utilize it and easily serve the purpose.

The static folder is normally named as public

Express code for specifying the static folder is:

app.use(express.static("public"));

Example of static file usage in an Express JS project

const express = require('express');
const https = require('express');
const bodyParser = require('body-parser');
const request = require("request");
const { response } = require('express');

const app = express();

app.use(express.static("public"));    //specifying static folder


app.get('/', function(req, res){
    res.sendFile(__dirname+'/signup.html');
});


app.listen(3000, function(){
    console.log("Server is running on port 3000");

Folder Stucture

Usage in the rendering HTML page

About the Author: smartcoder

You might like

Leave a Reply

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