注意
此页面生成自 serve-index README。serve-index
为给定路径提供包含目录列表的页面。
安装
这是一个可以通过 npm registry 获取的 Node.js 模块。通过 npm install
命令 进行安装。
$ npm install serve-index
API
var serveIndex = require('serve-index')
serveIndex(path, options)
返回中间件,该中间件提供给定 path
中目录的索引。
path
基于 req.url
的值,所以 req.url
为 '/some/dir
且 path
为 'public'
将查找 'public/some/dir'
。如果您正在使用诸如 express
的框架,您可以通过 app.use
更改 URL “基路径”(请参阅 express 示例)。
选项
Serve index 在 options 对象中接受以下属性。
filter
将此过滤函数应用于文件。默认为 false
。filter
函数对每个文件调用,签名为 filter(filename, index, files, dir)
,其中 filename
是文件名,index
是数组索引,files
是文件数组,dir
是文件所在的绝对路径(因此也是列表所在的目录)。
hidden
显示隐藏文件(以点开头的文件)。默认为 false
。
icons
显示图标。默认为 false
。
stylesheet
CSS 样式表的可选路径。默认为内置样式表。
template
HTML 模板的可选路径或渲染 HTML 字符串的函数。默认为内置模板。
如果给定字符串,该字符串将用作文件路径以加载模板,然后替换模板中的以下标记:
{directory}
替换为目录名称。{files}
替换为文件链接的无序列表的 HTML。{linked-path}
替换为目录链接的 HTML。{style}
替换为指定的样式表和嵌入的图像。
如果给定函数,该函数将以 template(locals, callback)
的形式调用,并且需要调用 callback(error, htmlString)
。提供的 locals 如下:
directory
是正在显示的目录(其中/
是根目录)。displayIcons
是一个布尔值,表示是否应该渲染图标。fileList
是目录中文件的排序数组。该数组包含具有以下属性的对象:name
是文件的相对名称。stat
是文件的fs.Stats
对象。
path
是directory
的完整文件系统路径。style
是默认样式表或stylesheet
选项的内容。viewName
是view
选项提供的视图名称。
view
显示模式。tiles
和 details
可用。默认为 tiles
。
示例
使用原生 node.js http 服务器提供目录索引
var finalhandler = require('finalhandler')
var http = require('http')
var serveIndex = require('serve-index')
var serveStatic = require('serve-static')
// Serve directory indexes for public/ftp folder (with icons)
var index = serveIndex('public/ftp', {'icons': true})
// Serve up public/ftp folder files
var serve = serveStatic('public/ftp')
// Create server
var server = http.createServer(function onRequest(req, res){
var done = finalhandler(req, res)
serve(req, res, function onNext(err) {
if (err) return done(err)
index(req, res, done)
})
})
// Listen
server.listen(3000)
使用 express 提供目录索引
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)