简体   繁体   English

Nodejs Express框架路由到文件

[英]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. 所以我想在我的浏览器上打开log.txt文件。

There are 2 ways you could do this (maybe more, I'm not a Node Pro yet). 有两种方法可以做到这一点(也许更多,我还不是Node Pro)。

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. 或者您可以使用fs模块并将其读入。

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. 我个人建议只在公共文件夹中静态地提供log.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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