使用 Express 列出服务器上的静态内容并 return 作为 JSON

List static content on server and return it as JSON using Express

我有一个提供静态文件的非常简单的应用程序:

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/files'));
app.listen(process.env.PORT || 8080);

我想通过响应 文件夹 的 GET 来让这个应用程序稍微智能一些。我的意思是,列出文件夹的完整文件列表,在 JSON.

例如,对于 localhost:8080/ 的 GET,我希望该应用程序 return:

[{
  "type" : "file",
  "name" : "file1.ext"
},
{
  "type" : "file",
  "name" : "file2.ext"
},
{
  "type" : "dir",
  "name" : "a-folder"
}]

而不是:

Cannot GET /

有没有办法通过扩展 Express 的静态行为来实现这一点? 如果没有,您会推荐什么方法?

编辑:我尝试使用 serve-index 中间件(以前称为 directory),效果很好但不幸的是直接 returns 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://yourdomain.com/files/file.jpg

编辑我刚刚意识到,你需要目录中的文件列表。

你有答案,那么,我将标记为重复

如评论 here 所述,也许安装节点实用程序 glob (npm install glob),并以这种方式在 /files 目录中为 GET 编写一些快速函数:

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 
  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);

});