Express.js - 以任何方式显示文件/目录列表?

时间:2011-06-09 14:12:53

标签: node.js express

使用Express.js有一种方法可以在访问没有索引文件的目录的URL时显示像apache这样的文件/目录列表 - 因此它会显示所有目录内容的列表?

是否存在我不知道的扩展程序或程序包?或者我自己要编码吗?

干杯伙计们,你摇滚! :)

5 个答案:

答案 0 :(得分:43)

目录列表中有一个全新的默认Connect middleware named directorysource)。它有很多风格,并有一个客户端搜索框。

var express = require('express')
  , app = express.createServer();

app.configure(function() {
  var hourMs = 1000*60*60;
  app.use(express.static(__dirname + '/public', { maxAge: hourMs }));
  app.use(express.directory(__dirname + '/public'));
  app.use(express.errorHandler());
});

app.listen(8080);

答案 1 :(得分:34)

从Express 4.x开始,目录中间件不再与express捆绑在一起。您将要下载npm模块serve-index

然后,例如,要在名为videos的应用程序根目录的目录中显示文件/目录列表,如下所示:

    var serveIndex = require('serve-index');

    app.use(express.static(__dirname + "/"))
    app.use('/videos', serveIndex(__dirname + '/videos'));

答案 2 :(得分:13)

以下代码将同时提供目录和文件

var serveIndex = require('serve-index');
app.use('/p', serveIndex(path.join(__dirname, 'public')));
app.use('/p', express.static(path.join(__dirname, 'public')));

答案 3 :(得分:4)

这将为您完成工作:(新版本的express需要单独的中间件)。例如。你把文件放在文件夹'文件'并且您希望网址为' / public'

var express = require('express');
var serveIndex = require('serve-index');
var app = express();

app.use('/public', serveIndex('files')); // shows you the file list
app.use('/public', express.static('files')); // serve the actual files

答案 4 :(得分:1)

内置的NodeJS模块fs提供了许多细粒度的选项

const fs = require('fs')

router.get('*', (req, res) => {
    const fullPath = process.cwd() + req.path //(not __dirname)
    const dir = fs.opendirSync(fullPath)
    let entity
    let listing = []
    while((entity = dir.readSync()) !== null) {
        if(entity.isFile()) {
            listing.push({ type: 'f', name: entity.name })
        } else if(entity.isDirectory()) {
            listing.push({ type: 'd', name: entity.name })
        }
    }
    dir.closeSync()
    res.send(listing)
})

请确保阅读有关路径遍历的安全漏洞。

相关问题