Serving static files using Restify

I was working with Node.js for building a REST API. For REST API module I was using restify. The restify is a simple and yet powerful node module. One of the use case of the API was, I had to serve static file for specific routing. I went through the docs and tried different things but couldn’t figure yet out at first. After hustling for hours,  me and Christian started to go deep into it and figured it out!

So in my case the configuration was  something like this


server.get(/.*/, restify.serveStatic({
    'directory': 'static_content',
    'default': 'index.html'
 }));

When restify internally resolve the path, it looks for ‘static_content/index.html’.

I have coded a very basic application to show it works, sample application looks like below:

In this sample application the static content (index.html) is in the same root as server.js as why ‘directory’: ‘.’.

Use package.json to install necessary module and start playing 🙂

Advertisements

5 comments

  1. jh · January 22, 2014

    I have a problem serving files from subfolders. For example: GET / and GET /index.html both work as expected. index2.html is served from folder test if I call GET /test but not if I call GET /test/index2.html. Same with assets like /test/style.css.

  2. kuanb · March 31, 2015

    Unable to access CSS, JS files linked to index.html. Does anyone have a solution?

    • mushfiq · April 1, 2015

      can you share how you are loading your static files and how you are defining it in ‘restify.serveStatic’?

  3. Lyn Taylor · January 31

    This works fine
    server.get(/.*/, restify.serveStatic({
    ‘directory’: ‘myPublic’,
    ‘default’: ‘testPage.html’
    }));
    But i changed the route slightly, and it does NOT work. Why?
    server.get(‘/test’, restify.serveStatic({
    ‘directory’: ‘myPublic’,
    ‘default’: ‘testPage.html’
    }));
    First case i call using http://localhost:8080, second case i use http://localhost:8080/test

  4. Danny · February 25

    I had to use this to get mine to work properly.

    server.get /\*.*/, restify.serveStatic(
    ‘directory’: ‘./public’
    ‘default’: ‘index.html’)

    Thank you, this is one of the only places I found to get close to the result I wished for!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s