Skip to content

Instantly share code, notes, and snippets.

@nycdotnet
Created August 20, 2015 15:18
Show Gist options
  • Save nycdotnet/83f0a0915a242b9a7a4a to your computer and use it in GitHub Desktop.
Save nycdotnet/83f0a0915a242b9a7a4a to your computer and use it in GitHub Desktop.
http self-request
// demo of web server and client request. Lines 17 or 18 can be used and it works.
import http = require('http');
class Test {
request: http.ClientRequest;
private Connect() {
console.log("connecting");
this.request = http.request({
hostname: "localhost",
port: 22440,
path: "/",
method: "post",
headers: {
"Transfer-Encoding": "chunked"
}
//}, (r) => this.OnResponse(r)); // this works
}, this.OnResponse); // and this works
this.request.write("");
this.request.end();
}
private OnResponse(response: http.IncomingMessage) {
console.log("STATUS: " + response.statusCode);
console.log("HEADERS: " + JSON.stringify(response.headers));
response.setEncoding("utf8");
response.on('data', (chunk: any) => {
console.log("BODY: " + chunk);
});
}
constructor() {
this.Connect();
}
}
(() => {
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(22440, 'localhost');
console.log('Server running at http://localhost:22440/');
var testConn = new Test();
})();
@fearthecowboy
Copy link

I initially didn't like that very much, but after doing something sad and silly, i thought about itmore, and have changed my mind, and like this very very much.

This doesn't break readability of the code at all, and actually implicitly marks a given function as an intended callback.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment