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.
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.
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.
There may some caase when we want to serve the directory with some different name, The same can be done like below:
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.