How to link files in NodeJS (+ let the user download the file when clicking it)?

I guess it is just a simple question but I can't solve it on my own.

(I'm using Express + NodeJS)

What I would like to have is a directory listing with the files contained in it. The files shall be linked so that a user could download them by just clicking the link (like the standard directory listing you get if you have e.g. a apache server without any index file).

To list the directory content I use

var fs = require('fs');
fs.readdir('./anydir', function(err, files){
    files.forEach(function(file){
        res.send(file);
    });
});

(Notice: I did not include any error handling in this example as you can see)

Now I tried to just link the file by modifying the

res.send(file)

to

res.send('<a href=\"' + file + '\">' + file + '<br>');

but this just prints out the error message:

Cannot GET /anydir/File

... because I did not handle every file request in app.js.

How can I achieve my goal mentioned above?

Just use express.directory and express.static as middleware, possibly with a user-defined middleware to set Content-Disposition headers.

This worked for me:

var fs = require('fs');
fs.readdir('/var/', function(err, files){
    files.forEach(function(file){
        res.write('<a href=\"' + file + '\">' + file + '<br>');
    });
});

You put the content with write() not send(). Try this and let me know. I can see the list of files displayed correctly. Hope this helps you.