13

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?

6 Answers 6

18

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"));
3
  • Could you explain this a little bit further? Will this just serve every file in a folder?
    – MaiaVictor
    Jan 29, 2013 at 6:09
  • Yes, it'll server every file in the directory you pass it. Jan 29, 2013 at 6:09
  • 3
    This is great, but is there an option to manually chose the files, or hidden a subfolder?
    – MaiaVictor
    Jan 29, 2013 at 6:11
12

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.

0
5

As mentioned in the accepted answer for this question, I'd recommend using http-server.

It can be started via command line without any config

cd /path/to/directory
http-server
2

Personally I prefer to server files from nginx (I also use it for gzip encoding, caching, SSL handling and load balancing) and node provides just the API. Maybe not the answer you're looking for but it offers interesting choices. Maybe you can have a look at this approach and find that you like it ;)

1

If you want a really simple way then I would like to show you my module (it is not only for static files) simpleS, install it using npm install simples.

Put all your files in a folder, for example files.

Here is the magic:

var simples = require('simples');

var server = simples(80);

server.serve('files');

/* if you want to catch the acces to a folder and to do something, try this:
server.serve('files', function (connection, files) {
    // Your application logic
    // For example show the files of the folder
});
*/

You don't need to care about the content type of the files, it will detect it automatically from file extension

2
  • simpleS would fail to serve static JSON files that were about 60kb. I could not find any configuration option that fixed this in the docs or searching. Using http-server (github.com/nodeapps/http-server) worked great.
    – kwcto
    Nov 5, 2013 at 22:44
  • @bayfrontconsulting, yes, I found this bug, it was related to a broken stream that was serving chunks of maximum 64KB length and stopped, I fixed this in version 0.4.9 which will come soon with a lot of improvements. Hope you will give it a second try :)
    – micnic
    Nov 6, 2013 at 8:03
1

I did the below changes to AUTO-INCLUDE the files in the index html. So that when you add a file in the folder it will automatically be picked up from the folder, without you having to include the file in index.html

//// THIS WORKS FOR ME 
///// in app.js or server.js

var app = express();

app.use("/", express.static(__dirname));
var fs = require("fs"),

function getFiles (dir, files_){
    files_ = files_ || [];
    var files = fs.readdirSync(dir);
    for (var i in files){
        var name = dir + '/' + files[i];
        if (fs.statSync(name).isDirectory()){
            getFiles(name, files_);
        } else {
            files_.push(name);
        }
    }
    return files_;
}
//// send the files in js folder as variable/array 
ejs = require('ejs');

res.render('index', {
    'something':'something'...........
    jsfiles: jsfiles,
});

///--------------------------------------------------

///////// in views/index.ejs --- the below code will list the files in index.ejs

<% for(var i=0; i < jsfiles.length; i++) { %>
   <script src="<%= jsfiles[i] %>"></script>
<% } %>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.