1

many question on stackoverflow and others website , some ones says NodeJS is Singlethread and someone says NodeJS is Multithread, and they have there own logic to be Singlethread or Multithread. But If a interviewer ask same question. what should I say. I am getting confusion here.

4
  • 3
    The Node.js runtime is a multithreaded program written in C++. But the JavaScript programs you can run in Node.js are all single-threaded, since JavaScript is a single-threaded language. Commented Oct 4, 2018 at 12:09
  • 2
    @AhmedFasih JavaScript (or ECMAScript, rather) is not defined to be single-threaded. In fact, it's by definition asynchronous (which doesn't imply multi-threading) since it defines Promises, which are asynchronous primitives by nature. There are JavaScript engines (like Nashorn) which use JVM threads to manage the async side of JavaScript (setTimeout, promise.then(), etc). Commented Oct 4, 2018 at 12:11
  • Thank you @MadaraUchiha! That is a much more accurate explanation. Even Node.js’ libuv uses threads to spread as much async work as possible to other cores right? Not just Nashorn? Commented Oct 5, 2018 at 0:40
  • @AhmedFasih Yes, but that's beside the point. Libuv does use OS threads, but in NodeJS, that's hidden from your code. Your JS code has no access to these threads, you get the event loop and one thread to work with. Commented Oct 5, 2018 at 9:40

2 Answers 2

7

The main event loop in NodeJs is single-threaded but most of the I/O works run on separate threads. You can make it multi-threaded by creating child processes. There is a npm module napajs to create a multi-threaded javascript runtime.

However,the 10.5.0 release has announced multithreading in Node.js. The feature is still experimental and likely to undergo extensive changes, but it does show the direction in which NodeJs is heading.

So stay tuned!!

Sign up to request clarification or add additional context in comments.

Comments

3

NodeJS runs JavaScript in a single threaded environment. You get to use a single thread (barring the worker_threads module, and spawning processes).

Under the scenes, NodeJS uses libuv, which uses OS threads for the async I/O you get in the form of the event loop.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.