- ExpressJS - Resources
- ExpressJS - Best Practices
- ExpressJS - Debugging
- ExpressJS - Error handling
- ExpressJS - Scaffolding
- ExpressJS - RESTful APIs
- ExpressJS - Authentication
- ExpressJS - Sessions
- ExpressJS - Cookies
- ExpressJS - Database
- ExpressJS - Form Data
- ExpressJS - Static Files
- ExpressJS - Templating
- ExpressJS - Middleware
- ExpressJS - URL Building
- ExpressJS - HTTP Methods
- ExpressJS - Routing
- ExpressJS - Hello World
- ExpressJS - Environment
- ExpressJS - Overview
- ExpressJS - Home
ExpressJS Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
ExpressJS - Serving static files
Static files are files that cpents download as they are from the server. Create a new directory, pubpc. Express, by default does not allow you to serve static files. You need to enable it using the following built-in middleware.
app.use(express.static( pubpc ));
Note − Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.
Note that the root route is now set to your pubpc dir, so all static files you load will be considering pubpc as root. To test that this is working fine, add any image file in your new pubpc dir and change its name to "testimage.jpg". In your views, create a new view and include this file pke −
html head body h3 Testing static file serving: img(src = "/testimage.jpg", alt = "Testing Image
You should get the following output −
Multiple Static Directories
We can also set multiple static assets directories using the following program −
var express = require( express ); var app = express(); app.use(express.static( pubpc )); app.use(express.static( images )); app.psten(3000);
Virtual Path Prefix
We can also provide a path prefix for serving static files. For example, if you want to provide a path prefix pke /static , you need to include the following code in your index.js file −
var express = require( express ); var app = express(); app.use( /static , express.static( pubpc )); app.psten(3000);
Now whenever you need to include a file, for example, a script file called main.js residing in your pubpc directory, use the following script tag −
<script src = "/static/main.js" />
This technique can come in handy when providing multiple directories as static files. These prefixes can help distinguish between multiple directories.
Advertisements