Node Newbie Node Newbie - 3 months ago 112
Node.js Question

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!

Answer

From a documentation:

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

But this will search files in the ./public/docs/public/ directory.
I prefer to use __dirname key here:

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

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