While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or
edited it to ensure you have an error-free learning experience. It’s on our list, and we’re working on it!
You can help us out by using the “report an issue” button at the bottom of the tutorial.
In Node.js and ExpressJS applications, there used to be a very simple way to deliver an HTML file or any other sort of file: res.sendfile()
. Delivering HTML files using Express helps make development quick and easy when you need a quick HTTP server.
Recently, this function has become deprecated by ExpressJS and if you try using the function, you’ll get an error saying that function is deprecated and you should use res.sendFile()
.
Using res.sendFile()
To use res.sendFile, we will need to pass in a path to the file.
We will also need to pull in the built-in path module so that we can link to the file.
Here is an example of using res.sendFile()
to deliver an HTML page.
var express = require('express');
var app = express();
var path = require('path');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
Sample Code
We’ll need a Node application to start. So you can create one by running the following commands:
- mkdir express-sendfile
- cd sendfile
- npm init
- npm install express --save
- touch server.js index.html
Now we have the foundation for our quick Node app. server.js
will be the file that will contain the route to serve our index.html
file.
server.js
var express = require('express');
var app = express();
var path = require('path');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Site</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<style>
body { padding-top:50px; }
</style>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>res.sendFile() Works!</h1>
</div>
</div>
</body>
</html>
Now after our server has been started using:
We can see our site in our browser!
Conclusion
res.sendFile() is a very easy function to use. Express provides a great many tools for Node users and we can even use this to deliver downloadable files or any files really.