Jonathan
Jonathan

Reputation: 543

How does a node process work?

Hi I'm new to node and I'm trying to understand how a node process is handled. I've read that synchronous methods should be avoided at all costs, and that require compiles/caches the file and subsequent calls use the cache vs. reading the from disk every time.

On line 7 of the boot file in the MVC example on the ExpressJS repo there is a call to readdirSync that loops all the controllers and instances them to dynamically create routes.

When a request is made to the server, what happens?

a) Launching the app compiles/caches it, routes and callbacks are stored in memory to serve all future requests.

b) The boot runs every request, controllers are read from disk and instanced every time a call to the server is made.

c) Something else?

If its a, I can see why the author would use a sync call. The code is cleaner, and blocking during the init stage isn't as bad as blocking during requests. If its b, wouldn't blocking at the start of every request greatly impact performance?

Thanks!

Upvotes: 0

Views: 80

Answers (2)

hexacyanide
hexacyanide

Reputation: 91799

The file is run during initialization, and only once. You can see that here:

require('./lib/boot')(app, { verbose: !module.parent });

In Node you don't generally want to block the main event loop, which is what synchronous functions tend to do. For example, say you have a HTTP handler that loads a file:

app.get('/', function(req, res) {
  res.send(fs.readFileSync('./file.log'));
});

This is done synchronously and will block the event loop until the file is fully loaded, preventing any other HTTP requests from being handled. Therefore, we generally cache things into memory during initialization to prevent blocking.

If cached during initialization, the file is only loaded once.

var file = fs.readFileSync('./file.log');
app.get('/', function(req, res) {
  res.send(file);
});

But an alternative way is to use a asynchronous read:

app.get('/', function(req, res) {
   fs.readFile('./file.log', function(err, data) {
     res.send(data);
   });
});

You generally don't want to do that because what if you have a high number of requests? You would be wasting I/O reading the same file from disk over and over again.

Upvotes: 2

Trevor Dixon
Trevor Dixon

Reputation: 24392

It's a) that happens. Your suppositions are all correct. The sync call is cleaner, and it only happens once during initialization. Express is careful not to do any io blocking inside request handlers.

Upvotes: 1

Related Questions