6. Attach Multiple Stream

Attach Multiple Streams

In this example, multiple streaming is dempnstrated.

  • Set TCP server on localhost port 6969.
  • Attach stream whenever a new client connects to the TCP server.
  • Stream debug message to TCP client

File : attachMultipleStream.js

const net = require('net');
const debug = require('pretty-debug');

var PORT = 6969;
var HOST = '0.0.0.0';

debug.setOptions({
	nodeMemoryMonitor:{
		fields: {
			rss: false,
			external: false
		}
	}
});

debug.info('Example : Attach Multiple Stream');

net.createServer(function(sock){
	debug.attachStream(sock);
	sock.on('end', function() {
		debug.detachStream(sock);
	}); 
}).listen(PORT, HOST);

function generateRandomLog(){
	debug.log('The quick brown fox jumps over the lazy dog');
	debug.info('The quick brown fox jumps over the lazy dog');
	debug.alert('The quick brown fox jumps over the lazy dog');
	debug.warn('The quick brown fox jumps over the lazy dog');
	debug.error('The quick brown fox jumps over the lazy dog');
	debug.critical('The quick brown fox jumps over the lazy dog');
}

setInterval(function(){
	generateRandomLog();
}, 678)

Run Example

To run the above example simply run the command below

$ node attachMultipleStream.js

Server Output

Server Output

Open TCP Client

To see the stdout stream of the server via TCP client, just simply connect to it and print the message.

A simple netcat command will do this work :

$ nc localhost -p 6969

Or write a simple TCP client on Node.js :

var net = require('net');

var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
	console.log('TCP Client Connected');
});

client.on('data', function(data) {
	process.stdout.write(data);
});

Client Output

Client Output

-----------------------------------------------------