2

I have a directory with some images in it that I want to make viewable in a browser.

This directory lives on my server at /public/images

Inside /public I also have other directories that I do not want to make public, hence making the entire /public directory viewable is not the solution.

How can I using the connect directory middleware make just my /public/images browsable?

Using the solution described here makes everything in /public viewable and trying the following doesn't work :

    app.use(exp.static(__dirname + '/public'));
    app.use(exp.static(__dirname + '/public/images'));
    app.use(exp.directory(__dirname + '/public/images'));
Rohad Bokhar
  • 104
  • 9
braitsch
  • 14,906
  • 5
  • 42
  • 37

2 Answers2

9

You have to mount your routes to a special path, like

app.use('/', exp.static(__dirname + '/public'));
app.use('/images', exp.static(__dirname + '/public/images'));
app.use('/images',exp.directory(__dirname + '/public/images'));

This way you can access the content of /public with the url / and the content of /public/image with the url /images

Zong
  • 6,160
  • 5
  • 32
  • 46
  • I tried this while wanting to make a root-level directory available and it didn't work. I just added a folder called /ndn as a sibling to /public and I want to use a test.js script in a client view file from /views where a script src points to "/ndn/test.js" - how? – Cody Feb 17 '13 at 11:31
  • @Cody at least with express@3.0.0 this works like a charm - just allow access to the root level directory with express static middleware. Maybe there's a bug in your code? –  Feb 17 '13 at 12:21
  • Please note that express.directory is no longer bundled hence supported in Express ^4.X.X. You can use serve-index for it. – danish.ahmad Oct 22 '20 at 11:16
1

Express 4:

npm install serve-index

--

var serveIndex = require('serve-index');

app.use('/images', express.static(__dirname + '/public/images'), serveIndex(__dirname + '/public/images'));
brycejl
  • 1,411
  • 17
  • 22