0

I have the following http server code

var server = http.createServer(function (req, response) {
    body = "";
    req.on("data", function (data) {
    body += data;
  });
  req.on("end", function (){
    parseRequest(body);
  });
}).listen(8080);

var parseRequest = function (data) {
  try {
    jsonData = JSON.parse(data);
    handleRequest(jsonData);
  }
  catch (e) {
    console.log("Json Parse Failed")
    console.log(e);
    response.writeHead(500);
    response.end("Json Parse Failed");
  }
}

I thought that the parseRequest function should be able to access it's variables in in its parent function's scope. Is there something I am doing wrong here?

The error I get is,

response.writeHead(500);
^
ReferenceError: response is not defined
3
  • 2
    Variable declared inside the scope of a function are limited to that scope unless declare globally. so you need parseRequest inside the same scope as response if you want it to use response. Commented Jun 25, 2015 at 6:19
  • "access it's variables in in its parent function's scope" - yes, it does. Only the scope of the createServer callback is not the parent scope of parseRequest. Move it inside there and it would work. Commented Jun 25, 2015 at 6:27
  • 1
    Btw, you are missing variable declarations for body and jsonData. Please use strict mode to avoid such accidental globals. Commented Jun 25, 2015 at 6:32

2 Answers 2

1

Change it to:

req.on("end", function (){
    parseRequest(response, body);
});

And then:

var parseRequest = function (response, data) { ...

And now you can access response. ;)

Sign up to request clarification or add additional context in comments.

9 Comments

I know I could do this, but it seems inefficient.
What is inefficient about this?
Inefficient? If you don't propagate the variables you need to your method scope, you have no chance to access them.
I checked, this worked in the chrome js console,a = function(b){x=b;d()};d = function(){console.log(x)};a("hi"); prints hi.
Because in this example, it's declared in the scope enclosing your function
|
0

Try this:

var server = http.createServer(function (req, response) {
  var body = "";
  req.on("data", function (data) {
    body += data;
  });
  var parseRequest = function (data) {
    try {
       var jsonData = JSON.parse(data);
       handleRequest(jsonData);
    } catch (e) {
      console.log("Json Parse Failed")
      console.log(e);
      response.writeHead(500);
      response.end("Json Parse Failed");
    }
  };
  req.on("end", function (){
    parseRequest(body);
  });
}).listen(8080);

2 Comments

Why would you create a new function per request if there is no need for it?
@SebastianNette: Now he's creating 3 instead of 2 functions per request. Doesn't seem to be a large difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.