How to Serve Static Content using Node.js ?
Last Updated :
27 Apr, 2020
Improve
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:
html
Filename: app.js
javascript
Steps to run the program:
- 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
- Now create a folder whose content you want to serve as static, For example, you can create a folder named public.
- Now add some static content to this public folder. In this case, there is a GeeksLogo.png image in public folder.
- 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. - Now create a EJS file like Demo.ejs and put this file in views folder.
<!DOCTYPE html>
<html>
<head>
<title>Static Middleware Demo</title>
</head>
<body>
<img src="/GeeksLogo.png" width="600" height="600" />
</body>
</html>
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")
})
- The project structure will look like this:
- 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
- Run app.js file using below command:
node app.js
- Open browser and type this URL:
http://localhost:8080/
- Then you will see the Demo.ejs page as shown below: