Sending Files

A great helper method in Express is the sendfile(filepath) method on the Response object. sendfile() uses a single function call to do everything that needs to be done to send files to the client. Specifically, the sendfile() method does the following:

Image Sets the Content-Type header to the type based on file extension.

Image Sets other appropriate headers, such as Content-Length.

Image Sets the status of the response.

Image Sends the contents of the file to the client by using the connection inside the Response object.

The sendfile() method uses the following syntax:

res.sendfile(path, [options], [callback])

path should point to the file that you want to send to the client. The options parameter is an object that contains a maxAge property that defines the maximum age for the content and a root property that is a root path to support relative paths in the path parameter. The callback function is called when the file transfer is complete and should accept an error as the only parameter.

Listing 18.6 shows how easy it is to send the contents of a file by using the sendfile() command. Notice that a root path is specified in line 8 so only the filename is required in line 6. Also notice that the callback function has code to handle the error. This code sends an image file, and Figure 18.5 shows that image displayed in a browser.

Listing 18.6 express_send_file.js: Sending files in a HTTP request from Express


01 var express = require('express'),
02 var url = require('url'),
03 var app = express();
04 app.listen(80);
05 app.get('/image', function (req, res) {
06   res.sendfile('arch.jpg',
07                { maxAge: 1,//24*60*60*1000,
08                  root: './views/'},
09                function(err){
10     if (err){
11       console.log("Error");
12     } else {
13       console.log("Success");
14     }
15   });
16 });


Image

Figure 18.5 An image file sent in an HTTP response to a client.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.154.121