user3492018
user3492018

Reputation: 15

Nodejs Express framework route to a file

New to express, wondering what is the best way to route to a single file in my directory. For example here is my simple server directory structure:

http://mywebroot.com
    |
    myfolder
    asset
        |
        log.txt

So I would like to have log.txt file being open on my browser.

Upvotes: 0

Views: 966

Answers (1)

Sterling Archer
Sterling Archer

Reputation: 22395

There are 2 ways you could do this (maybe more, I'm not a Node Pro yet).

First, you could serve the file statically with:

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

Or you could use the fs module and read it in.

app.get("/fileRoute",function(req,res) {
    fs.readFile("./path/to/file.ext","utf8",function(err,html) {
        res.send(html);
    });
});

Personally I suggest just serving log.txt statically in a public folder.

Upvotes: 3

Related Questions