Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting really confused with Node.js single thread execution model

Tags:

node.js

Ok, I'm learning Node.js but I couldn't wrap my mind around this waiting model. I'm learning it by reading The Node Beginner Book. In it there's a section about Blocking and Non-blocking operations. What I don't understand is the Non-blocking operations.

Here's the code:

var exec = require("child_process").exec;

function start(response) {
  console.log("Request handler 'start' was called.");

  exec("ls -lah", function (error, stdout, stderr) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write(stdout);
    response.end();
  });
}

function upload(response) {
  console.log("Request handler 'upload' was called.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello Upload");
  response.end();
}

exports.start = start;
exports.upload = upload;

The start function called exec, and exec executes ls -lah. Then the callback will wait for a response right? What if exec executes "find /", in my computer it would take about 30 seconds to finish the "find /" command. Since this is single threaded, if User 1 access start function, then within milliseconds User 2 also access the start function too. Then what happens? Does it mean that User 1 will get the response in 30 seconds while User 2 will need to wait 1 minute because User 1 is still fulfilling the "find /"?

Sorry if my question is too noobish. Thanks for reading!

like image 934
Kevin Lee Avatar asked Oct 06 '22 20:10

Kevin Lee


1 Answers

In node.js all I/O operations works asynchronously. Both find operations will be run in parallel. Try read this: Understanding the node.js event loop.

like image 127
Vadim Baryshev Avatar answered Oct 10 '22 02:10

Vadim Baryshev