0

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?

TorbenJ
  • 4,462
  • 11
  • 47
  • 84

2 Answers2

1

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

ebohlman
  • 14,795
  • 5
  • 33
  • 35
0

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.

sandino
  • 3,813
  • 1
  • 19
  • 24
  • yes it works but it only display the linked file but if you click on this link only the mentioned error is displayed – TorbenJ Jan 30 '13 at 15:18
  • you can not open files outside /public/ folder if you do not have permission to that particular folder. If what you want is a static server for files check this:http://stackoverflow.com/questions/9627441/cannot-get-with-connect-on-node-js, also note that the href link has only the name of the file not the full path maybe thats the problem try: res.write('' + file + '
    '); for example
    – sandino Jan 30 '13 at 17:15