I have a very simple app serving static files:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/files'));
app.listen(process.env.PORT || 8080);
I'd like to make this app slightly smarter by responding to GET for folders. I mean, to list the full list of files of the folder, in a JSON.
For instance, for a GET at localhost:8080/
, I would like the app to return:
[{
"type" : "file",
"name" : "file1.ext"
},
{
"type" : "file",
"name" : "file2.ext"
},
{
"type" : "dir",
"name" : "a-folder"
}]
instead of:
Cannot GET /
Is there a way to extend Express's static behaviour to achieve this? If not, what approach would you recommend?
EDIT: I tried to use the serve-index
middleware (formerly directory
), which works well but unfortunately returns directly html, when I need raw JSON.
As said in http://expressjs.com/starter/static-files.html
You need to use express.static:
Then you will be able to access the files as:
EDIT I just realized, you need the list of files in the dir.
There you have an API to do that: https://github.com/expressjs/serve-index
Also, there is a directory option in Express:https://stackoverflow.com/a/6524266/3617531
There you have the answers, then, I´ll mark as duplicate
As commented here, maybe installing node utility glob (
npm install glob
), and code some express function for GET in/files
dir this way:WALK MODE: (FOR SUBDIRS, AS REQUIRED)