This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

hapi.js - Serving static files

1:38 Node.js lesson by

hapi does not support serving static files out of the box. Instead it relies on a module called Inert. This lesson will cover serving static files using Inert's custom handlers.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

hapi does not support serving static files out of the box. Instead it relies on a module called Inert. This lesson will cover serving static files using Inert's custom handlers.

Avatar
Igor

Would make sense to mention about listing param as well

In reply to egghead.io

My Hapi server is set up to run on port 8000, and I've already registered the inert plugin. My browser is looking for a file called hapi.ping but it's not found. I'll add a route, watching for an HTTP get for the path /hapi.ping.

In the header function I'll use path.join to specify the path to my hapi.ping file and pass the path into the reply file method added by the inert plugin. Now when the browser is refreshed, the file asserts correctly. Inert also adds a custom route handler for serving files. To use it, I'll remove the handler function and add an object literal in its place.

The custom handler is called File, and its value should be the path to the file you want to serve through the route. I'll set it to the path to the hapi.ping file, refresh the browser, and the image is returned and displayed.

Surfing one file per route isn't very practical. That's why inert has a custom route handler for serving entire directories. I'll replace the file handler with one called Directory. The Directory handler should be an object with a path key that points to the directory you'd like to serve.

I'll give it a path to my public directory, then change the route path to a wildcard param that will catch any unmatched route, and look for a file to serve. Refreshing the browser shows that the hapi.ping file is now being served via the Directory handler.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?