serving static files with restify (node.js)
Asked Answered
S

3

24

I have the following code:

app.js

[...]

server.get(/\/docs\/public\/?.*/, restify.serveStatic({
  directory: './public'
}));

server.listen(1337, function() {
  console.log('%s listening at %s', server.name, server.url);
});

And I have the following file structure

app.js
public/
  index.html

So I try browsing:

http://localhost:1337/docs/public/index.html

and I get

{
  code: "ResourceNotFound",
  message: "/docs/public/index.html"
}

I tried with several variations, but none of them seemed to work.

I'm sure it should be something pretty obvious I'm missing

Spiro answered 17/3, 2013 at 17:29 Comment(0)
A
20

restify will use the directory option as a prefix for the entire route path. In your case, it will look for ./public/docs/public/index.html.

Assiut answered 17/3, 2013 at 17:53 Comment(1)
I'm finding restify to be terribly documented.Exhaustless
O
8
  1. The directory option is a prefix for your entire path.
  2. Relative paths are not working correctly in later versions of Restify (I tested 2.6.0-3, 2.8.2-3 - and they all produce the NotAuthorized error)

The solution now becomes:

server.get(/\/docs\/public\/?.*/, restify.serveStatic({
    directory: __dirname
}));

And then your static files will need to be in ./docs/public.
(__dirname is a global variable that contains the absolute path of the script you are running)

Obscurantism answered 22/11, 2014 at 9:59 Comment(2)
This did it for me!! The __dirname option is the key!Cece
There appears to be a bug for OSX that prevents using ./ syntax, so this was the only thing that worked for me. Thanks!Pericles
T
6

Based on @NdeeJim's answer, to anyone wondering how to serve ALL the static resources:

server.get(/\/?.*/, restify.plugins.serveStatic({
            directory: __dirname,
            default: 'index.html',
            match: /^((?!app.js).)*$/   // we should deny access to the application source
     }));
Tiger answered 30/9, 2015 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.