0

I know that javascript is single threaded, meaning only one operation runs at a time. Now consider the following scenario:

Scenario 1: I have a nodejs/express server running on port 5000, it has an endpoint, say, /convert-image. This endpoint uploads a png file and uses some third party library to convert it to a jpg file. (the conversion can either be synchronous or asynchronous)

Now, If I make 2 parallel api request to this endpoint, will it still run one thread to convert the files for each request?

Scenario 2: I have a file cron.js, that executes a long-running task, say it takes 10 mins to complete the task. If I open two tabs in my terminal, and run the cron.js file in both tabs, will it still create a single thread?

Phantom007
  • 2,079
  • 4
  • 25
  • 37
  • if you do 2 parallel api request, it will do them separately (asynchronously) – Nikita Mazur Jul 30 '21 at 10:25
  • @NikitaMazur You mean it will run two different threads or two different processes? – Phantom007 Jul 30 '21 at 10:33
  • 1
    Depends. If you use the syncrhon method, you block the event loop and your second requests has to wait till the event loop is done and can start processing the other request. https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ (Asynchron operations are pending callbacks) If you use the asyncrhon method it "schedule"/handle it as a pending callback and procceed with execution – Marc Jul 30 '21 at 10:39
  • You can read more here https://stackoverflow.com/questions/25568613/node-js-event-loop As @Marc mentioned syncron methods can still block the event loop, but api calls to node js are and should be asyncron, which lets a single thread process thousands of calls – Nikita Mazur Jul 30 '21 at 10:41
  • okay, so if I understood this correctly, in scenario 1, i can assume that if the api endpoint receives 1000+ request in a second, it wont hog my server memory, yes? (assuming the available memory of my server is 1 gb and the image conversion task takes 500 mb memory at a time) – Phantom007 Jul 30 '21 at 10:56
  • @Phantom007, did you check this link https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ mentioned above? `To prevent the poll phase from starving the event loop, libuv (the C library that implements the Node.js event loop and all of the asynchronous behaviors of the platform) also has a hard maximum (system dependent) before it stops polling for more events.` – ikhvjs Jul 30 '21 at 11:43

0 Answers0