Now that we know how to stream files let's do something more useful: Let's share files over http. Write a web server that streams a file via http.
To write an http server, you will need the http core node module.
When writing an http server, usually with http.createServer(function (req, res) { })
, the res
parameter
is a writable stream, so we can use the same tools we used in problem 1 to pipe the file to this stream.
You can build on the solution from the previous exercise. Here is ours:
var fs = require('fs')
var pump = require('pump')
// Any string pointing to a file on your harddrive will do, but the special
// `__filename` variable will always point to the current file (this file)
var filename = __filename
var file = fs.createReadStream(filename)
pump(file, process.stdout)
To test your solution, run it with node.
node server.js
And access it via curl or a regular web browser. If your server is running on port 3000, then run
curl localhost:3000
Validate that it downloads (outputs) the file that you expect.
When you are done click here to go to the next exercise