Archive
[nodejs] create a TCP time server
Problem
I found this exercise at https://github.com/workshopper/learnyounode and here is my solution. Write a TCP server that listens on the port provided by the first argument to your program. For each connection you must write the current date & 24 hour time in this format: “YYYY-MM-DD HH:mm” (example: “2015-11-23 16:11”).
Solution
We will use moment.js to suck less with dates and times.
#!/usr/bin/env node
"use strict";
var net = require('net');
var moment = require('moment'); // install with npm
const port = process.argv[2];
function main() {
console.log("The server is listening on port " + port + "...");
var server = net.createServer(function (socket) {
socket.end(moment().format('YYYY-MM-DD HH:mm') + "\n");
}).listen(port);
}
main();
Start it and the server will listen to incoming connections. When a request is processed, it doesn’t stop. It continues listening for the next connection.
Test it
Start the server and run the following command in another terminal:
$ nc 127.0.0.1 8000 2015-11-23 16:21
The command “nc” is the netcat command. Under Manjaro it’s in the gnu-netcat package.
