When Node.js performs an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.
This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.
In Node.js the new ECMAScript standards can be used without problems, as you don't have to wait for all your users to update their browsers - you are in charge of deciding which ECMAScript version to use by changing the Node.js version, and you can also enable specific experimental features by running Node.js with flags.
The most common example Hello World of Node.js is a web server:
To run this snippet, save it as a
server.js file and run
node server.js in your terminal.
This code first includes the Node.js
Node.js has a fantastic standard library, including first-class support for networking.
createServer() method of
http creates a new HTTP server and returns it.
The server is set to listen on the specified port and host name. When the server is ready, the callback function is called, in this case informing us that the server is running.
Those 2 objects are essential to handle the HTTP call.
The first provides the request details. In this simple example, this is not used, but you could access the request headers and request data.
The second is used to return data to the caller.
In this case with:
we set the statusCode property to 200, to indicate a successful response.
We set the Content-Type header:
and we close the response, adding the content as an argument to
See https://github.com/nodejs/examples for a list of Node.js examples that go beyond hello world.