2

I want to create a server and I want to get the script, CSS and the library.

I can get the file, but I don't know how to get a directory:

app.get('/app.js', function(req, res) {
    fs.readFile(__dirname + '/app.js', 'utf8', function(err, text){
        res.end(text);
    });
});

I want to get directory like above.

How can I do this?

peterh
  • 11,875
  • 18
  • 85
  • 108
LostCode
  • 533
  • 2
  • 6
  • 25

2 Answers2

4

in express you can define/set a public dir:

app.use(express.static(__dirname + '/public'));

everything in there will be served like from a normal "fileserver".
if you want to have directory listings, take a look at this:
Express.js - any way to display a file/dir listing?
or this
How do you get a list of the names of all files present in a directory in Node.js?

Community
  • 1
  • 1
Philipp Kyeck
  • 18,402
  • 15
  • 86
  • 123
2

If you are looking for function to read a directory fs.readDir should do the job for you. If you are looking for serving some static files it is better you use some framework such as "connect" (http://www.senchalabs.org/connect/static.html), instead of writing all by yourself.

May you share what problem are you trying to solve? Someone can give you a much more precise answer in that case.

Please note I am also newbie to node.

Philipp Kyeck
  • 18,402
  • 15
  • 86
  • 123
nvbalaji
  • 56
  • 5