Created
August 29, 2017 05:49
-
-
Save trygve-lie/cebe91ef1e74cd2b9b2aadc275b7fedc to your computer and use it in GitHub Desktop.
terminate-stream.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const { URL } = require('url'); | |
const http = require('http'); | |
// Simulate client making request to proxy and aborting mid flight | |
function fetch() { | |
console.log('request to proxy started'); | |
const get = http.get(new URL('http://127.0.0.1:3001'), (res) => { | |
res.setEncoding('utf8'); | |
let data = ''; | |
res.on('data', (chunk) => { | |
data += chunk; | |
}); | |
res.on('end', () => { | |
console.log('request to proxy ended', data); | |
}); | |
}).on('error', (error) => { | |
console.log('request to proxy error', error); | |
}); | |
setTimeout(() => { | |
console.log('abort request to proxy'); | |
get.abort(); | |
}, 300); | |
}; | |
// Http server | |
http.createServer((req, res) => { | |
console.log('server writes header'); | |
res.statusCode = 200; | |
res.setHeader('Content-Type', 'text/plain'); | |
setTimeout(() => { | |
console.log('server writes body'); | |
res.end('Hello World\n'); | |
}, 1000); | |
}).listen(3000, '127.0.0.1'); | |
// Proxy server | |
http.createServer((req, res) => { | |
console.log('proxy requesting server started'); | |
http.get(new URL('http://127.0.0.1:3000'), (r) => { | |
r.on('end', () => { | |
console.log('proxy request to server end'); | |
}); | |
r.pipe(res); | |
}); | |
res.on('error', () => { | |
console.log('proxy response error'); | |
}); | |
req.on('finish', () => { | |
console.log('proxy response finish'); | |
}); | |
req.on('close', () => { | |
console.log('proxy response close'); | |
}); | |
}).listen(3001, '127.0.0.1', () => { | |
fetch(); | |
}).on('error', () => { | |
console.log('haha'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment