Use ExpressJS to Deliver HTML Files

Chris Sevilleja
👁️ 272,292 views
💬 comments

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.

Table of Contents

    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

    Here's the code for that:

    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="//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:

    $ node server.js

    We can see our site in our browser!

    express-sendfile

    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.

    Chris Sevilleja

    176 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.