1'use strict'; 2 3const common = require('../common'); 4const fixtures = require('../common/fixtures'); 5 6if (!common.hasCrypto) 7 common.skip('missing crypto'); 8 9const assert = require('assert'); 10const http2 = require('http2'); 11const fs = require('fs'); 12const tls = require('tls'); 13 14const ajs_data = fixtures.readSync('a.js', 'utf8'); 15 16const { 17 HTTP2_HEADER_PATH, 18 HTTP2_HEADER_STATUS 19} = http2.constants; 20 21const key = fixtures.readKey('agent8-key.pem', 'binary'); 22const cert = fixtures.readKey('agent8-cert.pem', 'binary'); 23const ca = fixtures.readKey('fake-startcom-root-cert.pem', 'binary'); 24 25const server = http2.createSecureServer({ key, cert }); 26 27server.on('stream', (stream, headers) => { 28 const name = headers[HTTP2_HEADER_PATH].slice(1); 29 const file = fixtures.path(name); 30 fs.stat(file, (err, stat) => { 31 if (err != null || stat.isDirectory()) { 32 stream.respond({ [HTTP2_HEADER_STATUS]: 404 }); 33 stream.end(); 34 } else { 35 stream.respond({ [HTTP2_HEADER_STATUS]: 200 }); 36 const str = fs.createReadStream(file); 37 str.pipe(stream); 38 } 39 }); 40}); 41 42server.listen(0, () => { 43 44 const secureContext = tls.createSecureContext({ ca }); 45 const client = http2.connect(`https://localhost:${server.address().port}`, 46 { secureContext }); 47 48 let remaining = 2; 49 function maybeClose() { 50 if (--remaining === 0) { 51 client.close(); 52 server.close(); 53 } 54 } 55 56 // Request for a file that does exist, response is 200 57 const req1 = client.request({ [HTTP2_HEADER_PATH]: '/a.js' }, 58 { endStream: true }); 59 req1.on('response', common.mustCall((headers) => { 60 assert.strictEqual(headers[HTTP2_HEADER_STATUS], 200); 61 })); 62 let req1_data = ''; 63 req1.setEncoding('utf8'); 64 req1.on('data', (chunk) => req1_data += chunk); 65 req1.on('end', common.mustCall(() => { 66 assert.strictEqual(req1_data, ajs_data); 67 maybeClose(); 68 })); 69 70 // Request for a file that does not exist, response is 404 71 const req2 = client.request({ [HTTP2_HEADER_PATH]: '/does_not_exist' }, 72 { endStream: true }); 73 req2.on('response', common.mustCall((headers) => { 74 assert.strictEqual(headers[HTTP2_HEADER_STATUS], 404); 75 })); 76 req2.on('data', common.mustNotCall()); 77 req2.on('end', common.mustCall(() => maybeClose())); 78 79}); 80