Simple Servers

Basic Server

server-basic.js
'use strict'

const http = require("http")
let count = 0
http.createServer(function(req, res) {
    const message = `Received ${++count} requests so far`
    console.log(message)
    res.writeHead(200, { "Content-Type": "text/plain" })
    res.end(message)
})
.listen(8080)

Run it: node server-basic.js

Test it: curl http://localhost:8080

Server with Pause

server-pause.js
'use strict'

const http = require('http')
http.createServer(function (req, res) {
	res.writeHead(200, { 'Content-Type': 'text/plain' })
	res.write('hello\n')
	setTimeout(function () {
		res.end('world\n')
	}, 2 * 1000)
}).listen(8080)

Run it: node server-pause.js

Bench it: ab -n 100 -c 100 http://localhost:8080/

Echo Server

Run it: node server-echo.js

Talk with it: nc localhost 8080

Chat Server

Run it: node server-chat.js

Talk with it: nc localhost 8000

Supplemental

Echo Server with Transform Stream

Run it: node server-echo-transform.js

Talk with it: nc localhost 8080

Chat Server with Extras

Run it: node server-chat-extra.js

Talk with it: nc localhost 8080

Last updated

Was this helpful?