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 either:

  1. Follow the installation instructions from our node.js guide
  2. Install Occidentalis, a metapackage we've built which pulls down a collection of development tools.

For this guide, I'm relying on Occidentalis because it includes other useful software. There are detailed installation instructions on GitHub, but the short version is that you can open a terminal on your Pi and run the following:

curl -SLs https://apt.adafruit.com/install | sudo bash

This will take a while to run, depending on your network connection.

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.

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

var net = require('net');

var onConnection = function (socket) {

console.log('Server running at');

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:

./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.

Last updated on May 04, 2015 Published on Mar 26, 2015