How to set node server to run different requests simultaneously?

59 Views Asked by At

I was asked how to set node server to run different requests simultaneously. The question is like below: create a web server with only 1 route('/single'), in the controller run below code to imitate intensive CPU work:

const obj = {};
for(let i = 0; i < 2000000; ++i) {
    obj[i] = {[Math.random()]: Math.random()};
}
const jsonString = JSON.stringify(obj);
const obj2 = JSON.parse(jsonString);

So, if it takes 2 seconds run the request, then 10 requests it will run 20 seconds in a single thread mode. Now my task is set server to run different requests simultaneously, so run 10 requests will not take 20 seconds, but much less.

In my understanding in order to solve it, it is about how to use ASYNC FUNCTION and setTimeout method, I stuck here for few days. Please help me.

1

There are 1 best solutions below

0
On

You can use cluster to run the same node process on multiple threads, ideally the number of processing cores you have to handle concurrent requests with multiple cores.
More Details here: Node.js Cluster

or just use pm2 to achieve the same result without writing any code.