Creating Socket Client Connections

So far in this chapter, we’ve explored the server side of Node.js sockets. Here we’ll write a client program in Node.js to receive JSON messages from our net-watcher-json-service program. We’ll start with a naive implementation, and then improve upon it through the rest of the chapter.

Open an editor and insert this:

​ ​'use strict'​;
​ ​const​ net = require(​'net'​);
​ ​const​ client = net.connect({port: 60300});
​ client.on(​'data'​, data => {
​  ​const​ message = JSON.parse(data);
​  ​if​ (message.type === ​'watching'​) {
​  console.log(​`Now watching: ​${message.file}​`​);
​  } ​else​ ​if​ (message.type ...

Get Node.js 8 the Right Way now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.