Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving static files with restify

I am learning to use Node.js. Currently, I have a folder structure that looks like the following:

index.html server.js client   index.html   subs     index.html     page.html res   css     style.css   img     profile.png   js     page.js     jquery.min.js 

server.js is my webserver code. I run this from a command-line using node server.js. The contents of that file are:

var restify = require('restify');  var server = restify.createServer({     name: 'Test App',     version: '1.0.0' });  server.use(restify.acceptParser(server.acceptable)); server.use(restify.queryParser()); server.use(restify.bodyParser());  server.get('/echo/:name', function (req, res, next) {     res.send(req.params);     return next(); });  server.listen(2000, function () {     console.log('%s running on %s', server.name, server.url); }); 

As you can see, this server relies on RESTIFY. I've been told I must use RESTIFY. However, I can't figure out how to serve static files. For instance, how do I server the *.html, *.css, *.png, and *.js files in my app?

Thank you!

like image 840
Node Newbie Avatar asked Oct 09 '13 20:10

Node Newbie


2 Answers

From the documentation:

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

But this will search files in the ./public/docs/public/ directory.
If you want to not append request path to it, use appendRequestPath: false option.

I prefer to use __dirname key here:

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

The value of __dirname is equal to script file directory path, which assumed to be also a folder, where is public directory.

And now we map all /public/.* urls to ./public/ directory.


Now also exists serveStaticFiles plugin:

server.get('/public/*', // don't forget the `/*`      restify.plugins.serveStaticFiles('./doc/v1') ); // GET /public/index.html -> ./doc/v1/index.html file 
like image 141
vp_arth Avatar answered Sep 21 '22 05:09

vp_arth


According to my current restify version (v5.2.0)

the serveStatic has been moved into plugins, so the code would be like this

server.get(   /\/(.*)?.*/,   restify.plugins.serveStatic({     directory: './static',   }) ) 

Syntax above will serve your static files on folder static. So you can get the static file like http://yoursite.com/awesome-photo.jpg

For some reason if you want to serve the static files under specific path like this http://yoursite.com/assets/awesome-photo.jpg for example.

The code should be refactored into this

server.get(   /\/assets\/(.*)?.*/,   restify.plugins.serveStatic({     directory: `${app_root}/static`,     appendRequestPath: false   }) ) 

The option appendRequestPath: false above means we dont include assets path into the file name

like image 45
Aditya Kresna Permana Avatar answered Sep 19 '22 05:09

Aditya Kresna Permana