testing/xpcshell/node-http2/example/server.js

changeset 0
6474c204b198
equal deleted inserted replaced
-1:000000000000 0:e652745b7e13
1 var fs = require('fs');
2 var path = require('path');
3 var http2 = require('..');
4
5 var options = process.env.HTTP2_PLAIN ? {
6 plain: true
7 } : {
8 key: fs.readFileSync(path.join(__dirname, '/localhost.key')),
9 cert: fs.readFileSync(path.join(__dirname, '/localhost.crt'))
10 };
11
12 // Passing bunyan logger (optional)
13 options.log = require('../test/util').createLogger('server');
14
15 // We cache one file to be able to do simple performance tests without waiting for the disk
16 var cachedFile = fs.readFileSync(path.join(__dirname, './server.js'));
17 var cachedUrl = '/server.js';
18
19 // Creating the server
20 var server = http2.createServer(options, function(request, response) {
21 var filename = path.join(__dirname, request.url);
22
23 // Serving server.js from cache. Useful for microbenchmarks.
24 if (request.url === cachedUrl) {
25 response.end(cachedFile);
26 }
27
28 // Reading file from disk if it exists and is safe.
29 else if ((filename.indexOf(__dirname) === 0) && fs.existsSync(filename) && fs.statSync(filename).isFile()) {
30 response.writeHead('200');
31
32 // If they download the certificate, push the private key too, they might need it.
33 if (response.push && request.url === '/localhost.crt') {
34 var push = response.push('/localhost.key');
35 push.writeHead(200);
36 fs.createReadStream(path.join(__dirname, '/localhost.key')).pipe(push);
37 }
38
39 fs.createReadStream(filename).pipe(response);
40 }
41
42 // Otherwise responding with 404.
43 else {
44 response.writeHead('404');
45 response.end();
46 }
47 });
48
49 server.listen(process.env.HTTP2_PORT || 8080);

mercurial