As an asynchronous event-driven JavaScript runtime, Node.js is designed to buildscalable network applications. In the following "hello world" example, manyconnections can be handled concurrently. Upon each connection, the callback isfired, but if there is no work to be done, Node.js will sleep.
const { createServer } = require('node:http');const hostname = '127.0.0.1';const port = 3000;const server = createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World');});server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`);});
JavaScript
Copy to clipboardThis is in contrast to today's more common concurrency model, in which OS threadsare employed. Thread-based networking is relatively inefficient and verydifficult to use. Furthermore, users of Node.js are free from worries ofdead-locking the process, since there are no locks. Almost no function inNode.js directly performs I/O, so the process never blocks except when the I/O is performed usingsynchronous methods of Node.js standard library. Because nothing blocks, scalable systems are veryreasonable to develop in Node.js.
If some of this language is unfamiliar, there is a full article onBlocking vs. Non-Blocking.
Node.js is similar in design to, and influenced by, systems like Ruby'sEvent Machine and Python's Twisted. Node.js takes the event model a bitfurther. It presents an event loop as a runtime construct instead of as a library. In other systems,there is always a blocking call to start the event-loop.Typically, behavior is defined through callbacks at the beginning of a script, andat the end a server is started through a blocking call like EventMachine::run()
.In Node.js, there is no such start-the-event-loop call. Node.js simply enters the event loop after executing the input script. Node.jsexits the event loop when there are no more callbacks to perform. This behavioris like browser JavaScript — the event loop is hidden from the user.
HTTP is a first-class citizen in Node.js, designed with streaming and lowlatency in mind. This makes Node.js well suited for the foundation of a weblibrary or framework.
Node.js being designed without threads doesn't mean you can't takeadvantage of multiple cores in your environment. Child processes can be spawnedby using our child_process.fork()
API, and are designed to be easy tocommunicate with. Built upon that same interface is the cluster
module,which allows you to share sockets between processes to enable load balancingover your cores.
- Reading Time
- 3 min read
- Contribute
- Edit this page