【问题标题】:What's the simplest way to serve static files using express?使用 express 提供静态文件的最简单方法是什么?
【发布时间】:2013-01-12 15:41:32
【问题描述】:

我正在使用一种相当丑陋的方法:

var app = require('express')(),
    server = require('http').createServer(app),
    fs = require('fs');
server.listen(80);

path = "/Users/my/path/";

var served_files = {};
["myfile1.html","myfile2.html","myfile3.html"].forEach(function(file){
    served_files["/"+file] = fs.readFileSync(path+file,"utf8");
});

app.use(function(req,res){
    if (served_files[req.path]) 
        res.send(files[req.path]);
});

正确的做法是什么?

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    Express 有一个内置的中间件。它是 connect 的一部分,express 是基于它构建的。中间件本身使用send

    // just add the middleware to your app stack via `use`
    app.use(express.static(yourpath));
    

    在回答您的评论时,不,没有办法手动选择文件。虽然默认情况下中间件会忽略以. 为前缀的文件夹,因此不会提供名为.hidden 的文件夹。

    要手动隐藏文件或文件夹,您可以在static 之前插入自己的中间件,以便在请求到达之前过滤掉路径。以下内容将阻止从名为 hidden 的文件夹中提供任何文件:

    app.use(function(req, res, next) {
      if (/\/hidden\/*/.test(req.path)) {
        return res.send(404, "Not Found"); // or 403, etc
      };
      next();
    });
    app.use(express.static(__dirname+"/public"));
    

    【讨论】:

    • 你能再解释一下吗?这会只为文件夹中的每个文件提供服务吗?
    • 是的,它会为您传递的目录中的每个文件提供服务。
    • 这很好,但是否有手动选择文件或隐藏子文件夹的选项?
    【解决方案2】:

    我对索引 html 中的文件进行了以下更改以自动包含文件。这样当您在文件夹中添加文件时,它将自动从文件夹中提取,而无需将文件包含在 index.html 中

    //// THIS WORKS FOR ME 
    ///// in app.js or server.js
    
    var app = express();
    
    app.use("/", express.static(__dirname));
    var fs = require("fs"),
    
    function getFiles (dir, files_){
        files_ = files_ || [];
        var files = fs.readdirSync(dir);
        for (var i in files){
            var name = dir + '/' + files[i];
            if (fs.statSync(name).isDirectory()){
                getFiles(name, files_);
            } else {
                files_.push(name);
            }
        }
        return files_;
    }
    //// send the files in js folder as variable/array 
    ejs = require('ejs');
    
    res.render('index', {
        'something':'something'...........
        jsfiles: jsfiles,
    });
    
    ///--------------------------------------------------
    
    ///////// in views/index.ejs --- the below code will list the files in index.ejs
    
    <% for(var i=0; i < jsfiles.length; i++) { %>
       <script src="<%= jsfiles[i] %>"></script>
    <% } %>
    

    【讨论】:

      【解决方案3】:

      我个人更喜欢从 nginx 提供文件服务(我也将它用于 gzip 编码、缓存、SSL 处理和负载平衡),并且 node 只提供 API。也许不是您正在寻找的答案,但它提供了有趣的选择。也许你可以看看这种方法并发现你喜欢它;)

      【讨论】:

        【解决方案4】:

        如果您想要一个非常简单的方法,那么我想向您展示我的模块(它不仅适用于静态文件)simpleS,请使用npm install simples 安装它。

        将所有文件放在一个文件夹中,例如files

        这就是魔法:

        var simples = require('simples');
        
        var server = simples(80);
        
        server.serve('files');
        
        /* if you want to catch the acces to a folder and to do something, try this:
        server.serve('files', function (connection, files) {
            // Your application logic
            // For example show the files of the folder
        });
        */
        

        你不需要关心文件的内容类型,它会自动从文件扩展名中检测出来

        【讨论】:

        • simpleS 将无法提供大约 60kb 的静态 JSON 文件。我在文档或搜索中找不到任何解决此问题的配置选项。使用 http-server (github.com/nodeapps/http-server) 效果很好。
        • @bayfrontconsulting,是的,我发现了这个错误,它与提供最大 64KB 长度的块并停止的中断流有关,我在 0.4.9 版本中修复了这个问题,很快就会有很多改进。希望你再试一次:)
        【解决方案5】:

        正如this question 的已接受答案中所述,我建议使用http-server

        无需任何配置即可通过命令行启动

        cd /path/to/directory
        http-server
        

        【讨论】:

          【解决方案6】:

          如果您想在不使用 Express 的情况下获得解决方案(正如您明确要求的“简单”),请查看 node-static 模块。

          它允许您像适当的 Express 中间件一样为文件夹提供服务,但它也允许您仅提供特定文件。

          在最简单的情况下,它只是:

          var http = require('http'),
              static = require('node-static');
          
          var folder = new(static.Server)('./foo');
          
          http.createServer(function (req, res) {
              req.addListener('end', function () {
                  folder.serve(req, res);
              });
          }).listen(3000);
          

          如果您需要一些示例,请查看 GitHub 项目页面,其中有几个。

          PS:您甚至可以全局安装 node-static 并将其用作 CLI 工具,只需从您希望服务的文件夹中的 shell 运行它:

          $ static
          

          就是这样:-)!

          PPS:关于您的原始示例,最好在此处使用带有流的管道,而不是以同步方式加载所有文件。

          【讨论】:

            猜你喜欢
            • 2016-01-30
            • 2012-07-13
            • 2017-12-01
            • 2018-07-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-01-19
            相关资源
            最近更新 更多