I am currently reading into how Node.js works behind the scenes in detail. The question I have is about its single threaded architecture and the event loop. I am already familiar with most of it but one thing is confusing me. An online instructor said that it is okay for a heavy synchronous function to be called if it is in the "top-level" code. I understand that it runs before the event loop even starts but doesn't it still block other users since its on the single thread?
-
@RokoC.Buljan I am aware of that. My question is about a synchronous function that is ran before the event loop even starts.user11812210– user118122102019-07-20 13:45:30 +00:00Commented Jul 20, 2019 at 13:45
-
@RokoC.Buljan your statement is misleading. Node.js uses thread for IO or for Workers. On js context is always single-threaded, so async functions of one js context will run in the same thread.t.niese– t.niese2019-07-20 13:54:55 +00:00Commented Jul 20, 2019 at 13:54
-
No matter when a block of js code is executed. If it is blocking it will block the whole context. A worker or IO can still run in a separate thread, but the context to which the blocking code block belongs is blocked.t.niese– t.niese2019-07-20 13:56:25 +00:00Commented Jul 20, 2019 at 13:56
-
1@t.niese: Node.js only uses threads for disk I/O and DNS lookups. It uses the main thread for all other I/O (such as network I/O)slebetman– slebetman2019-07-20 14:09:26 +00:00Commented Jul 20, 2019 at 14:09
1 Answer
It is common to run synchronous operations as part of a server startup and this is perfectly OK. In fact, if you were not to use synchronous operations in server startup, the startup code may be a ton more complicated.
For example, the require() operation is synchronous and blocking. So, yes it's perfectly OK to use synchronous code in the server startup portion of your code.
But, once your server has started, using synchronous I/O code such as fs.readFileSync() in any sort of request handler can ruin the scalability of your server.
I understand that it runs before the event loop even starts but doesn't it still block other users since its on the single thread?
If the synchronous code is before the server has started serving requests, then there are no other users yet to block. It's just part of the code that gets the server going.
If the synchronous code is after the server has started serving requests, then yes it would block other requests from being processed while the synchronous code was running and that would be an undesirable thing because it would significantly reduce the scalability and responsiveness of your server.