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.
- Nodejs | Automatic restart NodeJs server with nodemon
- Understanding storage of static methods and static variables in Java
- What purpose does a <script> tag serve inside of a <noscript> tag?
- Nodejs | DNS
- Web-Socket in NodeJS
- Nodejs | DNS | setServers()
- Nodejs | Jimp
- Nodejs | GM thumbnail() Function
- Nodejs | GM magnify() Function
- Nodejs | GM flip() Function
- Nodejs | GM minify() Function
- Nodejs | GM threshold() Function
- Nodejs | GM whiteThreshold() Function
- Nodejs | GM whitePoint() Function
- Nodejs | GM write() Function
- Nodejs | GM flop() Function
- Nodejs | GM bordercolor() Function
- Nodejs | GM channel() Function
- Nodejs | GM implode() Function
- Nodejs | GM edge() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.