Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the simplest way to serve static files using express?

I'm using a rather ugly approach:

var app = require('express')(),
    server = require('http').createServer(app),
    fs = require('fs');
server.listen(80);

path = "/Users/my/path/";

var served_files = {};
["myfile1.html","myfile2.html","myfile3.html"].forEach(function(file){
    served_files["/"+file] = fs.readFileSync(path+file,"utf8");
});

app.use(function(req,res){
    if (served_files[req.path]) 
        res.send(files[req.path]);
});

What's the proper way to do it?

like image 339
MaiaVictor Avatar asked Jan 29 '13 06:01

MaiaVictor


2 Answers

Express has a built in middleware for this. It's part of connect, which express is built on. The middleware itself uses send.

// just add the middleware to your app stack via `use`
app.use(express.static(yourpath));

In answer to your comment, no, there is no way to manually select files. Though by default the middleware will ignore folders prefixed with ., so for example a folder named .hidden would not be served.

To hide files or folders manually, you could insert your own middleware before static to filter out paths before the request reaches it. The following would prevent serving any files from folders named hidden:

app.use(function(req, res, next) {
  if (/\/hidden\/*/.test(req.path)) {
    return res.send(404, "Not Found"); // or 403, etc
  };
  next();
});
app.use(express.static(__dirname+"/public"));
like image 101
numbers1311407 Avatar answered Sep 19 '22 10:09

numbers1311407


If you want to have a solution without using Express (as you asked for "simple" explicitly), check out the node-static module.

It allows you to serve a folder just like the appropriate middleware for Express, but it also allows you to serve only specific files.

In the simplest case it's just:

var http = require('http'),
    static = require('node-static');

var folder = new(static.Server)('./foo');

http.createServer(function (req, res) {
    req.addListener('end', function () {
        folder.serve(req, res);
    });
}).listen(3000);

If you need some examples, have a look at the GitHub project page, there are several of them.

PS: You can even install node-static globally and use it as a CLI tool by just running it from the shell inside the folder you wish to serve:

$ static

That's it :-)!

PPS: Regarding your original example, it would be way better to use piping with streams here instead of loading all the files in a synchronous way.

like image 32
Golo Roden Avatar answered Sep 18 '22 10:09

Golo Roden