Thursday, 11 May 2017

How to create a fake server for Node.js "net"?

Background

I have a use case where my application receives data from a machine every X seconds.

This application connects to that machine via an IP address and a Port, using the net official library from Node.js.

const net = require("net");
const config = require("./config.json");

const client = new net.Socket();

client.connect(config.readerPort, config.readerIP, () => console.log("Connected"));

client.on("close", () => console.log("Connection closed"));

client.on("data", console.log);

Objective

My objective here is to create a fake server that, just like the machine, allows my app to connect to it via an IP and a Port, and that emits events every X seconds as well.

To simulate this I have created a small app that prints 0 every 5 seconds:

setTimeout(() => {
    console.log(0);
}, 5000);

My objective is to, instead of printing to the console, to bind the small app to an IP and a port (localhost) and then make my app read from it.

Question

Using the net library from Node.js (or any other), how do change my fake server from printing to the console to sending that information to the localhost IP and a port?



via Flame_Phoenix