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?
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.
Express offers a built-in middleware to serve your static files and modularizes content within a client-side directory in one line of code.
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.
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
.
app.use("/css/myfile.css", express.static(__dirname + '/css/myfile.css'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With