How to Serve Static Files In Nodejs

By

How to Serve Static Files In Nodejs

By bangarsanju12

In this tutorial  we are going to see how we can serve static HTML pages from node JS application

In fact we are going to check how we can serve any static assets from our node JS application. by static resources we mean the CSS files the JavaScript files and static HTML files as well

There are variety of ways with which you can serve static resources in a simple node JS application let’s have a look at both the ways.

Without Using any External Dependencies

 In this way we are going to use simple plane NodeJS application . We’re going to create a simple NodeJS server and show our index.html located in the current directory.

We are only going to use http and fs Module of node.js let’s have a look how we can create a server which serves index.html .


const http = require('http')
const fs = require('fs')

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'content-type': 'text/html' })
  fs.createReadStream('index.html').pipe(res)
})

server.listen(process.env.PORT || 3000)

Now the problem with this approach one of the problem with this approach is it will not serve you the static assets it will only serve you the index.htm file located in the current directory so you can run this application using .

node app.js

Using Express as dependency

 So in this approach but we are going to do is where going to install Express as a dependency and use express.static  . So express.static  It is middleware function in Express JS which helps us to serve any kind of static assets  from our application .

Have a look  at the signature of the function .

express.static(root, [options])

Let’s say we have our CSS JavaScript and images located in our public directory.

in order to use public directory to serve static assets in my application we can specify that in following manner.

app.use(express.static('public'))

Now you can access your resources inside the public folder by simply accessing it through an URL as below.

https://localhost:3000/images/image1.jpeg"
https://localhost:3000/images/image1.jpeg

Please let us know in comments if you face any issue .

Leave a Comment