Express JS is a simple lightweight Node JS framework used to build back end applications quickly. In this tutorial, we will talk about the sendfile() method of Express JS with a proper example.

sendFile() method

Express JS added a new method called sendFile from v4.8.0 onwards. This method transfers the file at the location or path also sets the Content-Type response HTTP header field based on the filename’s extension.

Let's create an express js project quickly. Follow the steps below to create.

Open the command prompt inside the folder where you want to create the new project

npm init -y

Now create a new folder called public inside the project directory. Inside that public folder, let's add a new file called index.html with the following markup.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World!</title>
</head>
<body>
    <h1>Hello World!</h1>
</body>
</html>

Now, let's go to the root folder and add a file there called server.js. This file will contain our back end code where we will use the express sendfile.

const express = require('express');
const app = express();
// we are telling express to use public folder as static root
app.use(express.static('public')); 

// bind our app to a port and logs the output
app.listen(3000, function(){
    console.log("Listening on port 3000!")
});

// at the root of our application we will send the html file
// so when someone visits the website root(/) they will see the rendered html
app.get('/', function(req, res){
    res.sendFile('index.html');
});

Inside the express sendfile method we can pass the filename with extension. We can pass additional parameters too. Refer to the syntax below for that purpose.

res.sendFile(path [, options] [, callback function])

Finally, you know the use of express sendfile. Now go ahead and build some awesome web apps.