[英]Express.js - any way to display a file/dir listing?
使用Express.js ,当您访问没有索引文件的目录的 URL 时,是否可以显示文件/目录列表,如 apache 那样 - 所以它显示所有目录内容的列表?
是否有我不知道的扩展或 package 可以做到这一点? 还是我必须自己编写代码?
从 Express 4.x 开始,目录中间件不再与 express 捆绑在一起。 您需要下载 npm 模块serve-index 。
然后,例如,要在名为videos
的应用程序根目录中显示文件/目录列表,如下所示:
var serveIndex = require('serve-index');
app.use(express.static(__dirname + "/"))
app.use('/videos', serveIndex(__dirname + '/videos'));
目录列表有一个全新的默认连接中间件,名为directory
( source )。 它有很多风格,并有一个客户端搜索框。
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);
以下代码将同时提供目录和文件
var serveIndex = require('serve-index');
app.use('/p', serveIndex(path.join(__dirname, 'public')));
app.use('/p', express.static(path.join(__dirname, 'public')));
这将为您完成工作:(新版本的 express 需要单独的中间件)。 例如,您将文件放在“files”文件夹下,并且希望 url 为“/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
内置的 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)
})
请务必阅读路径遍历安全漏洞。
这段代码怎么样? 简单,可以下载文件。 我在这里找到了。
var express = require('express')
var serveIndex = require('serve-index')
var app = express()
// Serve URLs like /ftp/thing as public/ftp/thing
// The express.static serves the file contents
// The serveIndex is this module serving the directory
app.use('/ftp', express.static('public/ftp'), serveIndex('public/ftp', {'icons': true}))
// Listen
app.listen(3000)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.