Home > Net >  Why do we refactor Node.js code in different files
Why do we refactor Node.js code in different files

Time:08-05

I have a question. I am a beginner in node.js and I know that we refactor our server code into different files(like index.js, server.js, routes.js, etc.), to make our codebase more manageable and the code more readable.

However my senior informed me that we are splitting our code in different files so that node js can spawn a separate process for each file and several concurrent pieces of code are running at once.

This logic was a bit difficult to digest for me and I think that nodejs is single threaded, and we can use setTimeout/promises to send our async tasks to the Event queue. My understanding was that once we use a require statement, the code is directly imported to where we are importing it from.

Is my understanding wrong?

CodePudding user response:

I have a question. I am a beginner in node.js and I know that we refactor our server code into different files(like index.js, server.js, routes.js, etc.), to make our codebase more manageable and the code more readable.

Yes.

Also to make it more reusable.

However my senior informed me that we are splitting our code in different files so that node js can spawn a separate process for each file and several concurrent pieces of code are running at once.

No.

Modules do not create processes automatically.

To do that you need to either use a module which hooks into outside code (commonly achieved with node-gyp) or you need to do so explicitly by using a worker thread.

I think that nodejs is single threaded,

It isn't.

JavaScript runs code on a single event loop unless it is explicitly put elsewhere (e.g. with the aforementioned methods), but it does let you run multiple threads/processes. See worker threads above for example.

we can use setTimeout/promises to send our async tasks to the Event queue.

setTimeout just runs code later, not on a different thread.

Promises are used to manage asynchronous code, they don't make code asynchronous or move it to a different thread.

My understanding was that once we use a require statement, the code is directly imported to where we are importing it from.

The exported objects / primitives are imported to the importing module. The code is already compiled and dealt with.

CodePudding user response:

First of all, NodeJS is not single threaded as many seems to think.
It has 4 threads by default which are separated for different tasks such as working with I/O.

Our "main" javascript code works in one of these threads.

By our own purpose we can spawn more threads with help of worker_thread module.
These spawned threads requires some code to execute.
We have to give them the code by passing the path to file (or URL) into constructor.

I want to believe that my explanation is as clear as it could be :P

  • Related