What is Node.js (Node)?
- Display a message in a browser on the local machine when connecting to http://localhost:2000. The message reads, "This is a test of Node.js on a local computer."
- Return a message to the console when the command is run. The message states, "Node.js server running at http://127.0.0.1:2000/."
More details about the components in this script and the HTTP module in general can be found by referring to the HTTP topic in the official API reference documentation published by the Node.js organization.
How does Node.js work?
A Node application runs in a single process. Node does not create a new thread for every request, as is often the case with traditional server-side programs. In this way, a Node server can handle thousands of concurrent connections without having to contend with thread concurrency issues or the overhead multithreading brings.
Node.js is event-driven and runs asynchronously. Code written for the Node environment does not follow the traditional model of receive, process, send, wait and receive found in other systems. Instead, Node implements an event loop that processes incoming requests as they stack up in the event queue, handling small requests one after the other without waiting for responses.
This is a shift away from mainstream models that run larger, more complex operations and process several threads concurrently, with each thread waiting for its appropriate response before moving on.
The Node.js approach offers a major advantage over these models, according to its creator Ryan Dahl. Node does not block input/output (I/O) operations like more traditional approaches. This is in large part because Node functions do not perform I/O directly, which helps eliminate the potential for blocking. Blocking occurs only when using synchronous methods in the standard Node library, but that is the exception rather than the rule, making Node well suited for real-time applications with heavy concurrent workloads.
Node is not suited to every type of workload, however. For example, because of its single-threaded nature, Node might not be able to effectively run a processor-intensive web application that requires heavy server-side computations. The computational load could end up blocking incoming requests and degrading overall performance.
On the other hand, if Node appears to meet your needs in all other respects and the computational load is not too excessive, you might be able to implement that load as background processes in another language. Node can also be used as part of a microservices architecture that breaks the application into smaller parts.