-1

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.

Christian Baumann
  • 3,188
  • 3
  • 20
  • 37
Daniel
  • 31
  • 1
  • You are thinking in the right direction. You can wrap your logic inside a Promise, which will resolve with the Data that your request responds with. For eg. `function X () { return new Promise((res, rej) => { fetch('url').then((res) => res(res)).catch((err) => rej(err)); }); }` – phoenisx Oct 02 '20 at 13:56
  • Node is not meant to run very CPU intensive operations, because of its single-threaded nature. If your application is very CPU intensive, then there's probably something wrong with your design. Node is excellent at input/output intensive applications, like database or Elasticsearch calls. These operations cost nothing to Node, because they're performed by other processes, which allow them to be asynchronous and not block the thread. And so Node can perform a huge number of requests simultaneously. It's its job. – Jeremy Thille Oct 02 '20 at 14:21

1 Answers1

-1

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.

Shahriar Shojib
  • 867
  • 8
  • 16