Skip to content

Instantly share code, notes, and snippets.

@nycdotnet
Created August 20, 2015 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

Except, you're not getting the instance of the object (this), it's just treating it as a standalone function

// demo of web server and client request.  Lines 17 or 18 can be used and it works.
/// <reference path="typings/node/node.d.ts" />
import http = require('http');

class Test {
  request: http.ClientRequest;
  xyz : string;


  private Connect() {
    console.log("connecting");
    this.xyz = "happy"

    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) {
     // bad: you don't get the correct instance, so this.xyz doesn't work...
      console.log("which object: "+this.xyz );
      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();

})();

@nycdotnet
Copy link
Author

OK I see what you're saying.

Change the definition of OnResponse to arrow-style.

private OnResponse = (response: http.IncomingMessage) => {

instead of

private OnResponse(response: http.IncomingMessage) {

TypeScript (and ES6) lambdas automatically use a lexically-scoped this instead of the "it depends on how you called it" behavior of functions (or class members) declared in the traditional way.

If you look at the emit, you'll see that this gets captured as _this behind-the-scenes.

Let me know if this doesn't work for you.

@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