How to Serve Static Content using Node.js ?

Accessing static files are very useful when you want to put your static content accessible to the server for usage. To serve static files such as images, CSS files, and JavaScript files, etc we use the built-in middleware in node.js i.e. express.static.

Setting up static middleware:

  1. You need to create a folder and add a file. For example, app.js, To run this file you need to run the following command.
    node app.js
  2. Now create a folder whose content you want to serve as static, For example, you can create a folder named public.
  3. Now add some static content to this public folder. In this case, there is a GeeksLogo.png image in public folder.
  4. To serve this folder as static, you need the write this middleware in your index.js as follow:
    app.use(express.static(path.join(__dirname, 'public')))
    where path is the global object and __dirname holds current directory address. Views is the folder where our all web pages will be kept.
  5. Now create a EJS file like Demo.ejs and put this file in views folder.

Filename: Demo.ejs

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<head>
    <title>Static Middleware Demo</title>
</head>
<body>
  <img src="/GeeksLogo.png" width="600" height="600" />
</body>
</html>

chevron_right


Filename: app.js

filter_none

edit
close

play_arrow

link
brightness_4
code

const express = require('express')
const path = require('path')
const app = express()
  
// Static Middleware
app.use(express.static(path.join(__dirname, 'public')))
  
// View Engine Setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
  
app.get('/', function(req, res){
    res.render('Demo')
})
  
app.listen(8080, function(error){
    if(error) throw error
    console.log("Server created Successfully")
})

chevron_right


Steps to run the program:

  1. The project structure will look like this:
    project structure
  2. Make sure you have ‘view engine’ like I have used “ejs” and also install express using the following commands:
    npm install ejs
    npm install express
  3. Run app.js file using below command:
    node app.js

    Output of above command

  4. Open browser and type this URL:
    http://localhost:8080/
  5. Then you will see the Demo.ejs page as shown below:
    Ejs Demo Page

So this is how you can serve static content to our server which is very helpful in serving images, CSS, js file, etc in your project.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.