An HTTP route handler is an Express function assigned to a route and method. It receives a request and produces a response, letting a server define what happens when that route is called. section 2.6.3
Handlers can support different server tasks:
- A GET handler can read a video file and stream it to the browser through the HTTP response. section 2.6.5
- A POST handler can read a message from req.body, store it in a database, and return a success status. section 5.7.4
Listing 2.4 Simple streaming video server with Node.js
const express = require("express"); const fs = require("fs"); #1 const app = express(); const port = 3000; app.get("/video", async (req, res) => { #2 const videoPath = "../videos/SampleVideo_1280x720_1mb.mp4"; #3 const stats = await fs.promises.stat(videoPath); #4 res.writeHead(200, { #5 "Content-Length": stats.size, "Content-Type": "video/mp4", }); fs.createReadStream(videoPath).pipe(res); #6 }); app.listen(port); #1 Loads the (built-in) fs library so we can use the Node.js filesystem API #2 Sets the HTTP GET route handler for streaming video. This is a REST API for streaming video! Note the use of the async keyword to mark the route handler as an asynchronous function. Async route handlers are new in Express v5. #3 The path of the video file that we’ll stream to the browser. The video is loaded from the videos subdirectory in the chapter-2 code repository. #4 Retrieves the video file size. We’ll encode this in the HTTP header as a response to the web browser. Note that we’re using "fs.promises" instead of "fs" to gain access to filesystem functions that are compatible with JavaScript's async/await keywords. #5 Sends a response header to the web browser, including the content length and mime type #6 Streams the video to the web browser. Yes, it’s this simple!
See an async Express handler that reads file metadata, sets response headers, and pipes a video stream to the client. section 2.6.5





















