0

I have the below code for a file server and I would like to use and html page to show an index of the files that are available for download in the static folder "public1"

I currently can serve an html page if the user explicitly requests it but I can't make it automatically serve the html page. The commented out code is my attempt at serving the html page named "hello" by default. It doesn't work...

How can I make the html page display (by default) to the user that navigates to the ip address in a browser?

How can I make the html file show an index of files in the static folder?

So for this two part question, does anyone know how to do this? Can you point me in the right direction.

var express = require('express'); 
var server = express();
var port = 10001;

//server.get(__dirname + 'public1', function(req, res) {
//   res.send('Hello.html');
//});

server.use(express.static(__dirname + '/public1'));

server.listen(port, function() {
    console.log('server listening on port ' + port);
});
2
  • Why don't you just serve up that directory as a static folder then and save some of the hassle? Commented Jul 5, 2016 at 16:49
  • I think I understand what you are saying, but it doesn't show anything in the browser. I want the user to see what is available to be served. Commented Jul 5, 2016 at 16:51

1 Answer 1

2

The easiest way to do this is by using the serve-index and serve-static middleware that is available for express. The below example code works, just swap out the process.cwd() for whatever directory you'd like to serve.

const express = require('express');
const serveIndex = require('serve-index');
const serveStatic = require('serve-static');
const path = require('path');
const server = express();

const port = process.env.PORT || 3000;

function setHeaders(res, filepath) {
    res.setHeader('Content-Disposition', 'attachment; filename=' + path.basename(filepath));
}

const dirToServe = process.cwd();    

server.use('/', serveIndex(dirToServe, {icons: true}));
server.use('/', serveStatic(dirToServe, {setHeaders: setHeaders}));

server.listen(port, () => {
    console.log('listening on port ' + port);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.