Run Node.js in a Docker container


In this post, I explore how to run a Node.js web application in a Docker container based on the StrongLoop Process Manager image. I also have a requirement to export and deploy the Docker container to a server that lacks internet access.

docker-strongloop-pm.png

Create a new Node.js web app using express-example-app as the starting point

git clone https://github.com/strongloop/express-example-app.git

Head into the app folder and install dependencies

npm install

Start application using PM

slc start

Access http://localhost:3001 in a browser to ensure it works.

Shutdown PM

slc ctl shutdown

Create a new Docker container using StrongLoop PM image as the starting point

docker run --detach --restart=no --publish 8701:8701 --publish 3001:3001 --name strong-pm-container strongloop/strong-pm

Deploy example app by running following command in directory of app

slc deploy http://localhost:8701/ master

Access http://localhost:3001 in a browser to ensure it works.

Discover container’s id

docker ps -a

Commit container to a new image

docker commit 653811fd29f3 myimage

Save image to tar file

docker save -o myimage.tar myimage

Load image file in a new Docker instance (on another machine)

docker load -i myimage.tar

Run image in a new container

docker run --detach --restart=no --publish 3001:3001 --name strong-pm-container myimage

Access http://localhost:3001 in a browser to ensure it works.

Advertisements

JSON syntax highlighting in ScintillaNET


I am studying the excellent ScintillaNET code editing component, to enable basic JSON editing in a .NET application.

Inspired by the C# code highlighting example, here’s the code snippet to enable basic JSON syntax highlighting

net-scintilla-json.png

Make things smart with HomeKit and Raspberry Pi


As an avid iOS user I have been keen on using HomeKit. That’s when I read about a new – and currently free – HomeKit app in the iOS App Store called Hesperus. I don’t have a HomeKit compatible thing at home, but a quick internet search revealed that I could run a HomeKit compatible service called homebridge on a Raspberry Pi. This post only goes so far as configuring a fictitious light bulb plugin that can be controlled remotely.

Setup Raspberry Pi Image

I decided to download a headless (console-only) version of Raspbian called RASPBIAN JESSIE LITE. Instructions for setting up an SD card appropriately can be found here. I use Win32 Disk Imager on Windows to write images.

Powering the Raspberry Pi

I didn’t want to use an HDMI display with the Raspberry Pi, and wanted to power it using my laptop. I have used a USB to serial adapter to do that in the past. This time, I went with Adafruit’s USB Serial TTL cable as described in this lesson. That done, I was able to power up and login to the Raspberry Pi using a serial terminal. I tend to use screen on Linux or Mac OS X

screen /dev/ttyUSB0

Configuring Wi-Fi

RASPBIAN JESSIE LITE lacks a full-fledged user interface, making Wi-Fi configuration slightly painful. I am using a Wi-Fi stick and had some issues getting the driver to work. Hopefully, you’ve got a Raspberry Pi 3, or a compatible Wi-Fi stick that does not require too much tinkering. You can also use Ethernet. The following can be used to check whether your network interface can be listed

ifconfig

Look for an interface called wlan0 if using Wi-Fi, or eth0 if using ethernet.

This is how you can create a configuration file for your Wi-Fi access point

wpa_passphrase your_SSID your_passphrase > your_SSID.conf

Copy the contents of your_SSID.conf and paste them into /etc/wpa_supplicant/wpa_supplicant.conf using any text editor. I used vi thus

sudo vi /etc/wpa_supplicant/wpa_supplicant.conf

Having done that, Wi-Fi was up and running. I had internet access, and could access the Raspberry Pi on the local network via ssh.

Installing packages

A few additional Linux packages and configuration steps are required before homebridge may be installed. Packages can be installed thus

sudo apt-get update
sudo apt install nodejs npm git libavahi-compat-libdnssd-dev

Updating Node.js

The version of Node.js installed by apt-get is rather dated, and will not work with homebridge. To update node, use the following commands

sudo npm install -g n
sudo n stable

Install homebridge

homebridge can be installed using npm thus

sudo npm install -g homebridge

Find and install plugins

To do anything interesting with homebridge you’ll require a plugin, and have it configured in ~/.homebridge/config.json. One simple plugin called homebridge-fakebulb can be installed thus

sudo npm install -g homebridge-fakebulb

Its sample configuration file can be used to create the config.json file mentioned above. This is what my config.json looks like

{
    "bridge": {
        "name": "Homebridge",
        "username": "CC:22:3D:E3:CE:32",
        "port": 51826,
        "pin": "031-45-155"
    },

    "description": "This has some fake accessories",

    "accessories": [
        {
            "accessory":      "FakeBulb",
            "name":           "Test lamp",
            "bulb_name":      "Lamp 1"
        }
    ],

    "platforms": []
}

Use with HomeKit

Apple’s HomeKit has been app-less since launch. Siri is the only way you were able to control HomeKit devices. HomeKit has a rich API and it didn’t take long for paid apps to appear in the App Store. Hesperus is a new free app that I opted to use to control homebridge.

Here’s Hesperus with the Homebridge peripheral paired and working, showing the Test lamp device’s status. I can control the Test lamp (turn it on/off) anywhere I have an internet connection because I have an Apple TV (generation 4 – but 3 should also work) at home. Apple TV needs to be signed into the same iCould account as the iOS device paired with the Homebridge peripheral.

IMG_1979

Join multi-user chat with node-xmpp-client


XEP-0045 defines the XMPP protocol extensions required to join multi-user chat rooms, and receive and post messages. In this post, I use the node-xmpp-client library to join a multi-user chat room. Messages sent to the chat room are received but are not parsed.

node-xmpp-client can be installed using npm, as follows

npm i node-xmpp-client

Here’s a script that creates a new XMPP client, and sends a presence stanza to the XMPP server, to join a chat room

var Client = require("node-xmpp-client")

var jid = "user@domain"
var password = "password"
var room = "room@domain/nickname"

var client = new Client({
    jid: jid,
    password: password,
    preferred: "PLAIN"
})

client.on("online", function() {
    console.log("online")
    console.log("joining chat room")
    var stanza = new Client.Stanza("presence", {from: jid, to: room})
    client.send(stanza)
})

client.on("stanza", function(stanza) {
    console.log("Incoming stanza: ", stanza.toString())
})

client.on("error", function(e) {
    console.log(e);
})

process.on("SIGINT", function(code) {
    console.log("leaving chat room")
    var stanza = new Client.Stanza("presence", {from: jid, to: room, type: "unavailable"})
    client.send(stanza)

    setTimeout(function() {
        process.exit()
    }, 1000);
})

If you don’t specify a unique nickname, the XMPP server will likely reject the request to join the room. Modify the above script appropriately, save, and invoke node to execute it

node muc.js

If you get any errors, try setting the DEBUG environment variable as follows, and try again

export DEBUG=*

JSON-RPC


If your HTML5 application requires RPC (remote procedure call) semantics, JSON-RPC is an easy specification to implement. The code below allows sending requests and receiving responses, and leverages JQuery’s custom events to raise notifications (requests sent by server without an id).

        var nextId = 1;
        var messages = new Array();

        function Request(method, data) {
            this.method = method;
            // params is a C# keyword hence it is called data
            if (data)
                this.data = data;
        }

        Request.prototype.execute = function (callback) {
            if (callback) {
                this.id = nextId++;
                messages[this.id] = callback;
            }
            // Implement send so that the request gets sent to a server
            send(JSON.stringify(this));
        }

        // Whoever receives a stringified message from server must call dispatchMessage
        function dispatchMessage(message) {
            var o = JSON.parse(message);

            if (Array.isArray(o)) {
                dispatchBatch(o);
            } else {
                dispatch(o);
            }
        }

        function dispatchBatch(array) {
            array.forEach(function (message) {
                dispatch(message);
            })
        }

        function dispatch(message) {
            if (message.method) {
                // request
                $(document).trigger(message.method, message);
            } else {
                // response
                var callback = messages[message.id];
                if (callback) {
                    messages = messages.filter(function (elem) {
                        return elem.id == message.id; // remove
                    });
                    callback(message);
                } else {
                    console.log("Unknown response " + JSON.stringify(message));
                }
            }
        }

The following snippet shows how to handle a notification called foo, sent by the server

        $(document).on("foo", function (e, request) {
            // do something with request.data
        });

The following code demonstrates how to send a new request for a method called bar, and handle the corresponding response

            // data is some object that will be stringified
            var request = new Request("bar", data);
            request.execute(function (response) {
                // do something with response.error or response.result
            })

I’ll leave the server-side code to handle JSON-RPC as an exercise to the reader, or for a post in the future.

Using hints inside text fields instead of labels


The following code example demonstrates replacing labels with hints that appear as temporary values within text fields; akin to placeholder attribute in HTML5.

A custom attribute called data-hint-value contains the hint value to which a text field gets initialized. That value represents what typically would be the value of a label associated with the text field. It is cleared when the text field receives focus, and filled with hint value if text field is empty on blur.

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="shortcut icon" href="favicon.ico">
    <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
</head>
<body>
    <input id="name" type="text" data-hint-value="your name" />
    <script type="text/javascript">

        function setAllTextToHint() {
            $(":text").each(function (index) {
                hint = $(this).attr("data-hint-value");
                if (hint) $(this).val(hint);
            });
        }

        function isTextValueValid(id) {
            var ret = false;
            $(":text").each(function (index) {
                thisId = $(this).attr("id");
                if (thisId == id) {
                    hint = $(this).attr("data-hint-value");
                    value = $(this).val();
                    if (value == hint || value == "") {
                        alert("Please specify " + hint);
                        $(this).val(hint);
                        $(this).focus();
                        return;
                    } else {
                        ret = true;
                        return;
                    }
                }
            });
            return ret;
        }

        $(":text").focus(function () {
            hint = $(this).attr("data-hint-value");
            if ($(this).val() == hint)
                $(this).val("");
        });

        $(":text").blur(function () {
            hint = $(this).attr("data-hint-value");
            if ($(this).val() == "") {
                $(this).val(hint);
            }
        });
    </script>

setAllTextToHint is a helper function that sets all text fields to their hint values. isTextValueValid may be used to check whether a text field contains some value, and alerts the user when it does not. Tweak these as you see fit.

Manipulating JSON using Json.NET


Json.NET makes it convenient to manipulate JSON in C# using dynamic programming. Let’s start with a JSON representation we want to create

{
	"menu": {
		"id": "file",
		"value": "File",
		"popup": {
			"menuitem": [
				{
					"value": "New",
					"onclick": "CreateNewDoc()"
				},
				{
					"value": "Open",
					"onclick": "OpenDoc()"
				},
				{
					"value": "Close",
					"onclick": "CloseDoc()"
				}
			]
		}
	}
}

Here’s how the Json.NET object representation can be created in C# using dynamic programming

dynamic jobj = JObject.FromObject(new 
{
	menu = new
	{
		id = "file",
		value = "File",
		popup = new
		{
			menuitem = new []
			{
				new
				{
					value = "New",
					onclick = "CreateNewDoc()"
				},
				new
				{
					value = "Open",
					onclick = "OpenDoc()"
				},
				new
				{
					value = "Close",
					onclick = "CloseDoc()"
				}
			}
		}
	}
});

To serialize it

var json = JsonConvert.SerializeObject(jobj);
Console.WriteLine(json);

To deserialize JSON string representation to dynamic object

dynamic jobj = JsonConvert.DeserializeObject(json);
Console.WriteLine(jobj.menu.id);

It is fairly easy to extend the object representation and add new items

jobj.foo = new JArray()
{
	new JObject() {
		new JProperty("bar", 10)
	},
	new JObject() {
		new JProperty("bar", 20)
	}
};

That adds a new property to jobj called foo that references a new array containing two objects.