0

What are the best resources to learn Express.js? Can anybody explain the node.js framework,how exactly it works.

The nonblocking eventloop concept.

2 Answers 2

4

I've found the Express website explains things pretty well, and Express to be quite approachable for new users.

A multi-threaded system (Java and underlying JVM, for instance), contains many threads of execution that may each execute its own code instructions simultaneously (on a multi-core hardware CPU), or switched between, where each thread runs for a scheduled period of time, and then the OS schedules the next thread for execution.

Node programs are executed in the Node environment, which is single threaded, so there is only a single thread of code execution for the entire program and no multiple threads executing concurrently.

A simple analogy would be comparing the event loop with a standard programming construct, the while loop, which is exactly what it is.

while(1){
   // Node sets this up.  Do stuff.. Runs until our program terminates.
}

Starting a node program would start this loop. You could imagine your program being inserted into this loop.

If the first instruction in your program was to read a file from disk. That request would be dispatched to the underlying OS system call to read the file.

Node provides Asynchronous and Synchronous functions for things like reading a file, although the asynchronous is generally preferred because in a synchronous call, a problem with reading the file halts the entire program, in a single threaded system.

while(1){
  require('fs').readFileSync('file.txt');
  // stop everything until the OS reports the file has been read
}

In the (preferred) asynchronous version, the request to read the file is issued to the OS, and a callback function is specified, the loop continues. The program essentially waits for the OS to respond, and on the next loop (aka tick), your provided callback function (essentially just a location in memory) is called by the system with the result.

while(1){
  // 1st loop does this
  require('fs').readFile('file.txt', callback);

  // 2nd loop does this, system calls our callback function with the result
  callback(err, result)
}

There are anticipated advantages of a single threaded system. One is that there is no context switching between threads that needs to be done by the OS, which removes the overhead of performing that task in the system.

The other, and this is a hotly debated topic of how this compares against the way other systems and programming languages handle it - is the simplicity of programming using callback functions as a means to implement asynchronicity.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.