Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js - any way to display a file/dir listing?

With Express.js is there a way to display a file/dir listing like apache does when you access the URL of a directory which doesn't have a index file - so it displays a listing of all that directories contents?

Is there an extension or package that does this which I don't know of? Or will I have to code this myself?

Cheers guys, you rock! :)

like image 446
balupton Avatar asked Jun 09 '11 14:06

balupton


People also ask

How do you get a list of the names of all files present in a directory in JavaScript?

To get a list of the names of all files present in a directory in Node. js, we can call the readdir method. const testFolder = './folder/path'; const fs = require('fs'); fs.

What is __ dirname in Express?

__dirname is an environment variable that tells you the absolute path of the directory containing the currently executing file.

How do you read all files from a folder in js?

js, you can use the fs. readdir() method to list all files available in a directory. This method works asynchronously to read the contents of the given directory and returns an array of the names of the files in the directory excluding .


2 Answers

As of Express 4.x, the directory middleware is no longer bundled with express. You'll want to download the npm module serve-index.

Then, for example, to display the file/dir listings in a directory at the root of the app called videos would look like:

    var serveIndex = require('serve-index');      app.use(express.static(__dirname + "/"))     app.use('/videos', serveIndex(__dirname + '/videos')); 
like image 160
jbll Avatar answered Sep 29 '22 13:09

jbll


There's a brand new default Connect middleware named directory (source) for directory listings. It has a lot of style and has a client-side search box.

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); 
like image 30
yonran Avatar answered Sep 29 '22 12:09

yonran