-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_server.js
72 lines (53 loc) · 2.4 KB
/
file_server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
Write an HTTP server that serves the same text file for each request
it receives.
You will be provided with the location of the file to serve as the
first command-line argument. You must use the `fs.createReadStream()`
method to stream the file contents to the response.
Your server should listen on port 8000.
----------------------------------------------------------------------
HINTS:
The `http` core module has a method named `http.createServer()` that
takes a callback function. Unlike most callbacks in Node, the callback
used by `createServer()` is called more than once. Every connection
received by your server triggers another call to the callback. The
callback function has the signature:
function (request, response) { ... }
Where the two arguments are objects representing the HTTP request
and the corresponding response for this request. `request` is used to
fetch properties, such as the header and query-string from the request
while `response` if for sending data to the client, both headers and
body.
Both `request` and `response` are also Node streams! Which means that
you can use the streaming abstractions to send and receive data if
they suit your use-case.
`http.createServer()` also returns an instance of your `server`. You
must call `server.listen(portNumber)` to start listening on a
particular port.
A typical Node HTTP server looks like this:
var http = require('http')
var server = http.createServer(function (req, res) {
// request handling logic...
})
server.listen(8000)
Documentation on the `http` module can be found by pointing your
browser here:
/home/anca/lib/node_modules/learnyounode/node_apidoc/http.html
The `fs` core module also has some streaming APIs for files. You will
need to use `fs.createReadStream()` method to create a stream
representing the file you are given as a command-line argument. The
method returns a stream object which you can use `src.pipe(dst)` to
pipe the data from the `src` stream to the `dst` stream. In this way
you can connect a filesystem stream with an HTTP response stream.
----------------------------------------------------------------------
*/
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
var readStream = fs.createReadStream(process.argv[2]);
readStream.pipe(res);
readStream.on('error', function(err) {
res.end(err);
});
});
server.listen(8000);