Home > nodejs > [nodejs] create a TCP time server

[nodejs] create a TCP time server

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”).

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");


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 8000
2015-11-23 16:21

The command “nc” is the netcat command. Under Manjaro it’s in the gnu-netcat package.

Categories: nodejs Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: