How to Serve Static Content using Node.js ?
Setting up static middleware:
- 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.
- 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:
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.
Steps to run the program:
- 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:
- Open browser and type this URL:
- Then you will see the Demo.ejs page as shown below:
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.