Serve Static Files In Node.js

    Jan 28, 2017       by Pankaj Kumar

While app development with Node.js, there may many situations to serve images, css and javascript files. So in this article, I am going to exlain in detail. 

 

Serve Static Directories

Mainly while working with Node.js template engine, we may have images, js, css folder in our Node.js app root folder. By default any directory is not accessible  or we can't server any folder. We need to write code to make any folder to serve. In express framework on nodejs we use express.static() middleware function.

 

Suppose we have an image directory  and we want to serve images at froent end. Let's have a look code for doing  so.

 

 
const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname,'images')));
app.listen(3000);
 

 

This way we can make the image folder static so that it can be accessed at the frontend.

Now the images can be accessed at browser or at frontend code like below:

http://localhost:3000/images/user.jpg

http://localhost:3000/images/profile.jpg

 

In the same way, javascript and css can be served.

 

Virtual Path Prefix

There may some caase when we want to serve the directory with some different name, The same can be done like below:

 

 
const express = require('express');
const app = express();
const path = require('path');
app.use('/static',express.static(path.join(__dirname,'images')));
app.use('/static',express.static(path.join(__dirname,'public')));
app.listen(3000);
 

 

Now the image can be served with path static in place of image or public.

 

That’s all for now. Thank you for reading and I hope this article will be very helpful to understand the how to serve static directory in nodejs.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

 


WHAT'S NEW

Find other similar Articles here: