Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

The concept of how NodeJS runs and the space for each request

The concept of how NodeJS runs and the space for each request

Problem

I have been tinkering on NodeJS for a while now. I still don't seem to understand how Node actually runs. Maybe it's just that I can't shed off the PHP mindset. I know it's pretty different from PHP, but still I can't grasp the idea - especially when they keep repeating the terms event-loop, event-driven and REPL.

  • Does the code run "forever" when it gets started? Is it like a big 'ol browser window in the back-end that the all the clients look at and which listens to some sort of onRequest event from them?

  • Or is every Request an isolated sandbox? Where the code runs for every request, separated from the other requests?

I've seen demos of socket connection chat in the videos, and it seems like it runs like the first point describes. But wouldn't that be "wierd" where all people access the same "space"?

Problem courtesy of: Joseph the Dreamer

Solution

  1. Node code need not run forever. The typical use case you see uses Node as an http server (which by the way is one of the selling points of Node; a basic http server in about 5 lines of code) which therefore runs forever.
  2. Individual requests are isolated because they are handled or responded to in callbacks. Callbacks use a concept called closures which ensures that the state of the callback is maintained when it is called. So each response would be a callback which persists it's state. Here's a nice link about closures and callbacks.
  3. These callbacks run asynchronously so the main event loop is free to handle further requests.
Solution courtesy of: almypal

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

The concept of how NodeJS runs and the space for each request

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×