简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM