We'll begin, in our index.js file, by requiring the fs, http, and pump modules:
const fs = require('fs')
const http = require('http')
const pump = require('pump')
Now let's create our HTTP server and pump instead of pipe our big file stream to our response stream:
const server = http.createServer((req, res) => {
const stream = fs.createReadStream('big.file')
pump(stream, res, done)
})
function done (err) {
if (err) {
return console.error('File was not fully streamed to the user',
err)
}
console.log('File was fully streamed to the user')
}
server.listen(3000)
Piping many streams with pump
If our pipeline has more than two streams, we simply pass all of them to pump: pump(stream1, stream2, stream3, ...).
If our pipeline has more than two streams, we simply pass all of them to pump: pump(stream1, stream2, stream3, ...).
Now let's run our server:
$ node index.js
If we use curl and hit Ctrl + C before finishing the download, we should be able to trigger the error state, with the server logging that the file was not fully streamed to the user:
$ curl http://localhost:8080 # hit Ctrl + C before finish