Basic Server
'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
'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
'use strict'
const net = require('net')
net.createServer(function (socket) {
socket.write('Talk to me.\n')
socket.on('data', function (data) {
socket.write(data.toString().toUpperCase())
})
}).listen(8080)
Run it: node server-echo.js
Talk with it: nc localhost 8080
Chat Server
'use strict'
// Application
const net = require('net')
let sockets = []
net.createServer(function (socket) {
sockets.push(socket)
socket.write('Talk to me.\n')
socket.on('data', function (data) {
for (let i = 0; i < sockets.length; ++i) {
sockets[i].write(data)
}
})
socket.on('end', function () {
const index = sockets.indexOf(socket)
sockets = sockets.slice(0, index).concat(sockets.slice(index + 1))
})
}).listen(8080)
Run it: node server-chat.js
Talk with it: nc localhost 8000
Supplemental
Echo Server with Transform Stream
'use strict'
class UC extends require('stream').Transform {
_transform (data, encoding, next) {
next(null, data.toString().toUpperCase())
}
}
class Reverse extends require('stream').Transform {
_transform (data, encoding, next) {
next(null, data.toString().split('').reverse().join(''))
}
}
require('net').createServer(function (socket) {
socket.write('Talk to me.\n')
socket.pipe(new UC()).pipe(new Reverse()).pipe(socket)
}).listen(8080)
Run it: node server-echo-transform.js
Talk with it: nc localhost 8080
'use strict'
// Application
const net = require('net')
let count = 0
const sockets = {}
function broadcast (message) {
for (const key in sockets) {
if (sockets.hasOwnProperty(key)) {
sockets[key].write(message)
}
}
}
net.createServer(function (socket) {
sockets[socket.index = count++] = socket
socket.write('Hello user ' + socket.index + '\n')
broadcast('User ' + socket.index + ' joined\n')
socket.on('data', function (data) {
broadcast('User ' + socket.index + ' says: ' + data.toString())
})
socket.on('end', function () {
delete sockets[socket.index]
broadcast('User ' + socket.index + ' left\n')
})
}).listen(8080)
Run it: node server-chat-extra.js
Talk with it: nc localhost 8080