Getting Started with Node.js on an Embedded Single Board Computer Running Linux

The purpose of this guide is to assist in installing node.js on a Single Board Computer running Linux, and creating a simple, lightweight web server application which serves up a “Hello, world!” page. Once it is complete you can add further functionality to extend it on your own.        Home

These instructions will be based on the TS-7680 single board computer, but can also be generally applied to other embedded systems. With that said, there are some challenges you may encounter while installing Node.js on other embedded systems, such as:

    • Software on an embedded system typically gets upgraded less frequently or is even frozen at a specific version due to development and testing methodology and constraints.
    • Developers of general purpose software, and those that package that software, typically do so with the users of desktop and server systems in mind.
    • V8, Google’s open source high-performance JavaScript engine used by node.js, dropped support for armv5 (and requires VFPv2) as of v8 version 3.18 circa April 2013. The highest version of node that will run on these CPUs is v0.10.x. A lot of stuff will still run, but there are some packages that require a later version of node.js to function.

To install Node.js on our board, it is first necessary to note that the Node.js package started to be introduced to package manager repositories around 2015. The TS-7680 comes with Debian 8 (Jessie), which has the Node.js package available. For boards with older distribution versions it’s slightly more complicated, but we’ll note the additional steps along the way.

For boards running Debian Jessie use the following commands:

apt-get update
apt-get install nodejs npm

There are several dependencies, and you will be prompted to continue. Hit enter at this prompt to continue.

Debian Wheezy Backport
For older boards that are running Debian Wheezy there is a backport. For these you will need to make sure that wheezy-backports is in the file /etc/apt/sources.list and if not use vi or another editor to add the following line:

deb http://http.debian.net/debian wheezy-backports main

Then update and install the nodejs-legacy package.

apt-get update
apt-get install nodejs-legacy

Check with your specific distribution for appropriate backport software repositories.

The npm command to invoke the Node.js Package Manager is not included in the nodejs-legacy package. You will need to install it manually. To install npm manually, run the following command:

curl https://www.npmjs.com/install.sh | sh

This will take a few minutes to run. Note that as of the time of this writing, npm version was 3.9.5. If all goes well it should print a list of modules installed followed by “It worked”.

For older boards running pre-Wheezy distributions of Debian it may be possible to install node.js by building from source.

Pro Tip: Before installing, make sure the date and time are set correctly, to avoid certification issues when downloading npm. If there is an NTP server on your network you can run the command below, replacing the IP address with that of your NTP server:

ntpdate 192.168.0.xx

If there is not an NTP server available, you can set the time manually using the date command with arguments appropriate to the version of date that you are using.

Once node.js is installed, try running it at the command prompt.

node

If you get the following error:              Home

/usr/sbin/node: No such file or directory

Then run the following command:

ln -s /usr/bin/nodejs /usr/sbin/node

If node runs successfully you will see a console prompt “>”. You can begin typing javascript statements to play around with Node.js, or hit Control+D to exit.

Next, pick or create a directory for node to run in (e.g. /root/node), change to that directory, and run npm init. Hitting enter to all the prompts will create default values which are fine.

To demonstrate how easy it is to create a lightweight web server, the first package we will install is express. Use the following command:

npm install express http https

The full API for express can be found here. However, for our simple server we only need to know a handful of calls.

First create a text file called hello.js in the node directory you picked earlier. The first step will be to establish all the dependencies that we use:

// DEPENDENCIES AND SETUP
// ===============================================
var fs = require("fs")
var express = require("express"),
    http = require("http"),
    https = require("https"),
    app = express(),
    port = Number(8080)

Pro Tip: As a convention, the PORT environment variable is used to tell your web server what port to listen on. If this variable is unset, a default value of 8080 is used. To invoke the server on a different port, prepend the invocation of node with an assignment to the port variable, e.g.

PORT=2000 node hello.js

The above example would start the server on port 2000. You’ll need to specify a different port if something is already using the default port, otherwise it is up to you what port you want to use.

We use the built-in filesystem module fs for accessing files. After we call require()to get access to our express and https modules we initialize the appvariable by calling the function returned by our express package (to be used below), and setup the port we are running on to either be a value we specify on the command line, or 8080 if nothing was specified.

Pro Tip: In addition to the basic web server package we are installing https to support SSL. With fast CPUs, self-signed certificates for internal servers, and free certificates for Internet-facing servers, there is no reason to not secure every web connection for privacy and against eavesdropping and hackers. However, these are a few extra (non-coding) support tasks that must be performed up front and which are not covered by this guide – steps that by themselves require more work than the entirety of creating our web server – so we will show how to support both HTTP and HTTPS at the same time.

To support SSL it is only necessary to read in our SSL key information and make an additional call to start the server. This requires that you create a subdirectory named ssl and copy the private key, certificate, and chain of trust to the files privkey.pem, cert.pem, and chain.pem files, respectively. Creating these files is beyond the scope of this guide, and if you do not want to use SSL for this demo, you may omit these lines. However they are included to show how simple it is to get SSL support in node.js:

var privateKey  = fs.readFileSync("ssl/privkey.pem", "utf8")
var certificate = fs.readFileSync("ssl/cert.pem", "utf8")
var ca = fs.readFileSync("ssl/chain.pem","utf8")
var credentials = {key: privateKey, cert: certificate, ca: ca}

Now we need to define our “routes”. This is what express uses to map URLs to functions which return content for those URLs. Let’s create a root page that displays a “Hello, World” message.

// ROUTES
// ===============================================

// Define the root page route which serves up a static page
app.get("/", function(req, res) {
    console.log("get /")
    res.send(<!doctype html><html><head><title>Hello, world!</title></head><body><H1>Hello, world!</H1></body></html>\n")
})

We have embedded the HTML code to server for the root page directly in the call to send the response.

As of node.js version 4.0, support for template strings is present, so the above string could be converted to the more readable:

res.send(`
<!doctype html>
<html>
  <head>
    <title>Hello, world!</title>
  </head>
  <body>
    <H1>Hello, world!</H1>
  </body>
</html>`)

The Debian Jessie node package is 0.10.29, so to use template strings you would need to manually compile and install a newer version.

We can also define a default route, which will service all requests to URLs other than those we have specified. If we don’t do this, the default is to return a “404 Not Found” error for those pages.    Home

app.use(function(req, res){
    console.log("default")
    res.send("You have taken a wrong turn.")
})

Now all that is left is to start the server. We will start an HTTP server on the specified port.

// START THE SERVER
// ===============================================

app.listen(port, function() {
    console.log("HTTP listening on port ",port)
})
If you loaded your SSL certificates you can start the HTTPS server on the next higher port by adding the following code immediately before or after the above code:

https.createServer(credentials, app).listen(port+1,function() {
    console.log("HTTPS listening on port ",port+1)
})

That’s it! Now it is time to run the server. From the same directory, run the following command:

node hello.js

You should see the following output (omitting the HTTPS if you didn’t add that):

HTTP listening on port  8080
HTTPS listening on port  8081

Now make sure your board has a valid network configuration and open a web browser on the same network and enter the IP address of your board, e.g. if your board’s IP address is 192.168.2.38 you would enter http://192.168.2.38:8080 or https://192.168.2.38:8081 in the URL bar of your browser. Hit enter and the page should load, server right off the board! The console will also display a message indicating that a page was served.

You’ve now learned how to get started with Node.js on a single board computer running Linux. Please feel free to use the comment section below to help us improve this article or if you have any questions. Now, go and build something amazing!                       Home

Leave a Reply

Your email address will not be published. Required fields are marked *