Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 232
James Vickers Avatar asked Jul 13 '12 15:07

James Vickers


People also ask

How do I serve a static file in node JS?

In your node application, you can use node-static module to serve static resources. The node-static module is an HTTP static-file server module with built-in caching. First of all, install node-static module using NPM as below. After installing node-static module, you can create static file server in Node.

Can Express serve static files?

Express offers a built-in middleware to serve your static files and modularizes content within a client-side directory in one line of code.

Which express JS function is used to serve static files?

To serve static files such as images, CSS files, and JavaScript files, use the express. static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets.


2 Answers

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.

like image 132
ebohlman Avatar answered Sep 30 '22 17:09

ebohlman


app.use("/css/myfile.css", express.static(__dirname + '/css/myfile.css')); 
like image 39
Greg Bacchus Avatar answered Sep 30 '22 17:09

Greg Bacchus