A Tiny Network Listener with Node.js

As an interesting alternative to netcat, we can write a few lines of node.js.

So what is node? Well, according to the official site:

Node.js® is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

For more detail on what this means, check out our Node.js Embedded Development on the Raspberry Pi.

Installing Node.js

In order to proceed, we'll need a working install of node. For that, you can follow the installation instructions from our node.js guide.  Once that's done, come back here and proceed.

Streaming From Network to Standard Output: listener.js

Next, have a look at some code in the Adafruit-RasPipe repository we cloned last time around.

Download: file
cd Adafruit-RasPipe
nano listener.js
Download: file
#!/usr/bin/env node

var net = require('net');

var onConnection = function (socket) {
  socket.pipe(process.stdout);
};

net.createServer(onConnection).listen(5280);
console.log('Server running at 127.0.0.1:5280');

This creates a simple network server which listens for connections on port 5280. When a connection is established, the function in onConnection runs with a new stream contained in the socket variable. We then tell socket to pipe its input to process.stdout, which as you might guess is the standard output for the current process.

You can test this by running:

Download: file
./listener.js | raspipe_pitft.sh

And sending output via netcat or

Why node.js? Again, check out the guide:

Why is it worth exploring node.js development in an embedded environment? JavaScript is a widely known language that was designed to deal with user interaction in a browser.  Thanks to node.js, we can now use JavaScript outside of the browser, and even interact with hardware on devices such as the Raspberry Pi.

Tools like netcat are sufficient for lots of simple cases, but if you want to build a full-fledged network application in a robust programming language with lots of libraries available, node can be a great starting point.

This guide was first published on Mar 26, 2015. It was last updated on Mar 26, 2015. This page (A Tiny Network Listener with Node.js) was last updated on Jul 18, 2019.