Leo Jiang
Leo Jiang

Reputation: 26243

How does a Node.js server process requests?

Let's assume I have the following code. I'm using ExpressJS, but I don't think the server part is much different from vanilla Node.js.

var express=require('express');

var settings=JSON.parse(fs.readFileSync('settings.json','utf8')); // does this run only once (when the server starts)?

app.get('*',function(req,res){
  res.write(fs.readFileSync('index.html')); // does this block other requests?

  setTimeout(function(){
     someSlowSyncTask(); // does this block other requests?
  },1000);

  res.end();
});

In the example above, does the first readFileSync run once when the server starts, or does it run each time the server receives a request?

For the second readFileSync, does it prevent Node from processing other requests? In other words, do all the other requests have to wait until readFileSync finishes before Node processes them?

Edit: I added the setTimeout and someSlowSyncTask. Do they block other requests?

Upvotes: 0

Views: 1613

Answers (2)

bryanmac
bryanmac

Reputation: 39306

You should avoid synchronous methods on a server. They are available as a convenience for single user utility scripts.

The first one runs only once since it is a synchronous method. The * get route is not setup until after it returns.

The second will run when any http request comes to the server. And yes, it will block the whole server for the duration of that synchronous call (I/O cost to open and read the contents of the file). Don't do that.

There are plenty of articles on the internet around understanding the node event loop. For example, here and here

Upvotes: 5

brandonscript
brandonscript

Reputation: 73044

You're correct. Your first readFileSync will execute once when the server is first started.

The second readFileSync will occur each time you receive a request, but because it exists in the callback of res.end() (remember - Node.js is inherently non-blocking), you can receive any number of requests in a non-blocking fashion so long as your internal functions are also written to be non-blocking (e.g. have a callback). In your case, however, the timeout is not written asynchronously and will thus block the server from responding until it's complete.

Upvotes: 1

Related Questions