2

I would like to know if it is possible to specify a subdirectory for the filesystem root or the document root for requests of static resources (if there's any such distinction) in node.js.

I know that I can do it by concatenating an absolute path from the root, but I'm wondering if it can be done on an application-wide level.

I haven't found anything in the documentation supports it, but perhaps I'm overlooking it.


EDIT: I should mention that I'm not interested in using a 3rd party library at this point.

user113716
  • 318,772
  • 63
  • 451
  • 440

3 Answers3

3

Check out expressjs

http://expressjs.com/guide.html#configuration

Specifically

app.use(express.static(__dirname + '/public', { maxAge: oneYear }));

Express/connect has a 'static' middleware for this use case. There are other smaller packages just for static file serving, however, express is nice and well maintained.

Josh
  • 12,602
  • 2
  • 41
  • 47
  • Thanks for your answer, but I should have specified that I prefer to do it without a 3rd party library. I'd like to know if it is directly possible in node.js. If not, I'd assume that *express* is just doing the same sort of concatenation. – user113716 May 27 '11 at 21:38
  • https://github.com/senchalabs/connect/blob/master/lib/middleware/static.js#L105-215 – Josh May 27 '11 at 21:45
  • @Patrick since the code is available on github, then yes, it is possible. The main thing is knowing how to properly serve the resources up. A better option would be to look at something like nginx, which I'm going to be looking at this weekend for my own server. – jcolebrand May 27 '11 at 22:05
  • @drachenstern: I've used nginx. Liked it much better than Apache. What do you mean about the code being available on github? Are you talking about Express? – user113716 May 27 '11 at 22:12
2

The API does not allow you to do what you're asking for directly. You will need to use string concat.

jcolebrand
  • 15,889
  • 12
  • 75
  • 121
  • 2
    That's too bad. With a global setting on the application level, it would seem that all those concats could be avoided. – user113716 May 27 '11 at 22:55
0

I've tried the following script with nodejs and works well. it takes the current path as document root to serve.

app.js

var http = require('http');
var express = require('express');
var app = express();
app.use(express.static('./'));
var server = http.createServer(app);
server.listen(8080,'127.0.0.1',function() {
    console.log('listen to 127.0.0.1:8080');
});

the reference is here: http://expressjs.com/starter/static-files.html

morel
  • 1