2

I'm new to JavaScript and am trying to teach myself using code posted online. I'm unsure of the way arguments are passed into various functions at various levels.

For instance, in the node.js "Hello World" example (reproduced below), where do the 'req' and 'res' variables come from and how does the client call the server and pass this information to it (and get the result) !?!

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
3
  • 1
    req and res are formal parameters of the function expression function (req, res) {...} that is passed to createServer. They are effectively local variables of the function. createServer will then call the function, passing values to those variables, which are used by the function, e.g. res.writeHead(...) uses the value passed to res (hopefully an object with a writeHead method). Commented Jun 30, 2015 at 22:22
  • When you call to "http.createServer" you are passing an anonymous function that will be used by method "createServer". The core of node has the hard job, managing connections and creating the "request" and "response" objects that you are using on your anonymous function. Commented Jun 30, 2015 at 22:30
  • Hey people, Thanks for answering. I believe I get what the res and req are within the function definition itself. The tricky bit is how a function with no name (anonymous) nested inside another function (or method) is called from somewhere else and returns information to that calling place. Commented Jul 1, 2015 at 15:14

3 Answers 3

2

It's just a function body that is passed to the createServer method. The variables req and res don't exist as they are not variables, they are the function parameters, and those names are commonly used for readability, but in no way are obligatory - for example, the code would work the same if you did:

http.createServer(function (a, b) {
  b.writeHead(200, {'Content-Type': 'text/plain'});
  b.end('Hello World\n');
}).listen(1337, '127.0.0.1');

You know, just like when you define a function:

function someFunction(firstParam, secondParam) {
    // do something with firstParam and secondParam
}

But I'm not sure how a function with no name (anonymous) nested inside another function (or method) is called from somewhere else.

See if this helps you understand:

function add(a,b){return a+b}
function sub(a,b){return a-b}

function math(f, x, y) {
  alert(f(x, y));
}

math(add, 1, 2);
math(sub, 8, 4);
// pass in anon function - multiplication
math(function(a, b){return a * b}, 2, 5);

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

4 Comments

Hey Shomz, Thanks for answering. The function part itself is clear enough. But I'm not sure how a function with no name (anonymous) nested inside another function (or method) is called from somewhere else.
Hey, you're welcome! I've updated my answer to help you understand that. Btw. not sure why you accepted the answer that hints how createServer works instead of answering your question about passing functions.
Hey, Thanks... that makes things very clear. As for accepting the other answer, I plead noobness. Accepted it in haste and didn't know I could undo it.
Haha, no worries, I'm glad I could help. Welcome to SO! :)
1

Req -> Http (https) Request Object. You can get the request query, params, body, headers and cookies from it. You can overwrite any value or add anything there. However, overwriting headers or cookies will not affect the output back to the browser.

Res -> Http (https) Response Object. The response back to the client browser. You can put new cookies value and that will write to the client browser (under cross domain rules) Once you res.send() or res.redirect() or res.render(), you cannot do it again, otherwise, there will be uncaught error.

req = {
    _startTime     :    Date, 
    app            :    function(req,res){},
    body           :    {},
    client         :    Socket,
    complete       :    Boolean,
    connection     :    Socket,
    cookies        :     {},
    files          :     {},
    headers        :    {},
    httpVersion    :    String,
    httpVersionMajor    :    Number,
    httpVersionMinor    :     Number,
    method         :    String,  // e.g. GET POST PUT DELETE
    next           :    function next(err){},
    originalUrl    :    String,     /* e.g. /erer?param1=23¶m2=45 */
    params         :    [],
    query          :    {},
    readable       :    Boolean,
    res            :    ServerResponse,
    route          :    Route,
    signedCookies  :    {},
    socket         :    Socket,
    url            :    String /*e.g. /erer?param1=23¶m2=45 */
}

res = {
    app            :    function(req, res) {},
    chunkedEncoding:    Boolean,
    connection     :     Socket,
    finished       :    Boolean,
    output         :    [],
    outputEncodings:    [],
    req            :    IncomingMessage,
    sendDate       :    Boolean,
    shouldkeepAlive    : Boolean,
    socket         :     Socket,
    useChunkedEncdoingByDefault    :    Boolean,
    viewCallbacks  :    [],
    writable       :     Boolean
}

Comments

1

Have a look at the docs. They help: https://nodejs.org/api/http.html#http_http_createserver_requestlistener

http.createServer is creating an instance of http.Server. http.Server is an event emitter, which can emit several events, including "request."

The function you pass in as a parameter is the RequestListener. The function you are passing in is the requestListener which is bound to the "request" event.

So you are creating an instance of http.Server, which emits events and calls functions in response to those events. Suppose your instance of http.Server is http_server

Underneath the hood, http_server probably does something like:

http_server.on('request', [yourFunction])

Node implicitly sends req and res into your function. So every time a client makes a request to your server, it emits the "request" event. Then since [yourFunction] is bound to the request event, it gets called with the req and res parameters passed in.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.