With Node.js it is really easy to set up a simple server. Below I’ve collected some examples I’ve found and added a short explanation to each one.
Basic HTTP server
One of the most simple servers in Node.js is the following HTTP server. It will create a local server listening on port 8080
. Every request triggers a single (and highly unoriginal) response.
Start the server and test it with curl
:
$ node basic-http-server.js
$ curl http://127.0.0.1:8080
Server with a delayed response
This is a slight variation on the previous example. Instead of returning the response immediately and ending the connection, it will first tell you to have a bit more patience. After a short wait, it will send you the rest of the content. Notice that in the meantime the connection is kept open.
Start the server and check the time per request with the Apache benchmarking tool:
$ node delayed-response.js
$ ab -n 100 -c 100 http://127.0.0.1:8080/
If you use curl
to request the URL, you will see the first response immediately, followed by the next one after 2 seconds. In the browser you won’t see anything until the entire response is received. This is just how the different clients deal with the server’s response.
Echo server
In this example we do not need the http
module, instead we use the more low level net
module. This server will wait for data that is sent and return it in uppercase.
Start the server and talk to it. Since this is not a HTTP server, we use the nc
command.
$ node echo-server.js
$ nc 127.0.0.1 8080
Chat server
Start the server and connect to the server from at least two terminal windows. Now you can talk to each other.
$ node chat-server.js
$ nc localhost 8080
Static file server
Start the server and test it by requesting several URLs. If the requested file doesn’t exist, it will return a 404 status code and corresponding response message.
$ node static-file-server.js
$ curl http://127.0.0.1:8080/static-file-server.js
$ curl http://127.0.0.1:8080/not-found
Note: These are just simple examples. Probably you shouldn’t use it in real world code. However, they are really useful in understanding how the basics of Node.js work and even how servers and clients interact with each other.