node.js, express.js - What is the easiest way to serve a single static file?

Viewed 36678

I have already seen and made use of:

app.use("/css", express.static(__dirname + '/css'));

I do not wish to serve all files from the root directory, only a single file, 'ipad.htm'. What is the best way to do this with the minimum amount of code, using express.js?

6 Answers

If you precisely want to serve a single static file, you can use this syntax (example base on the original question, ipad.htm under root directory):

app.use('/ipad.htm', express.static(__dirname, {index: 'ipad.htm'}));

The default behaviour of express.static(dir) is that it will try to send an 'index.html' file from the required dir. The index option overrides this behaviour and lets you pick the intended file instead.

Quick example building on JoWie's answer:

npm install connect-static-file

npm install express

var express = require('express');
var staticFile = require('connect-static-file');

var path = 'pathto/myfile.txt';
var options = {};
var uri = '/';
var app = express();
var port = 3000;

app.use(uri, staticFile(path, options));

app.listen(port, () => console.log(`Serving ${path} on localhost:${port}${uri}`));
Related