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

node.jsExpress

node.js Problem Overview


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?

node.js Solutions


Solution 1 - node.js

res.sendFile(path_to_file); is all you need; it will automatically set the correct headers and transfer the file (it internally uses the same code as express.static).

In express versions less than 4, use sendfile instead of sendFile.

Solution 2 - node.js

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

Solution 3 - node.js

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.

Solution 4 - node.js

I published a small library for serving single static files: https://www.npmjs.com/package/connect-static-file

npm install connect-static-file

var staticFile = require('connect-static-file'); app.use('/ipad', staticFile(__dirname + '/ipad.html'));

The main difference with express.static is that it does not care about the request url, it always serves that file if the route matches. It does not suddenly start serving an entire directory if you name your directory "ipad.html".

Solution 5 - node.js

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}`));

Solution 6 - node.js

 fs.createReadStream(path).pipe(res);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames VickersView Question on Stackoverflow
Solution 1 - node.jsebohlmanView Answer on Stackoverflow
Solution 2 - node.jsGreg BacchusView Answer on Stackoverflow
Solution 3 - node.jsye olde noobeView Answer on Stackoverflow
Solution 4 - node.jsJoWieView Answer on Stackoverflow
Solution 5 - node.jsStejiView Answer on Stackoverflow
Solution 6 - node.jsPickelsView Answer on Stackoverflow