Reporting Rasp Pi data on a Node.js web server

Lead Image © Alexander Sidorov, 123RF.com

Pi Nodes

Combine great hardware projects that use the Raspberry Pi GPIO pins and a Node.js web server that interacts with the underlying operating system and hardware, and you have a winning team.

Reading values from sensors connected to Raspberry Pi (Rasp Pi) GPIO pins and displaying the results on the command line is satisfying, but being able to access your sensors remotely is where things start getting useful. The best way to do that is to use a tried and tested medium, the web, and the way to do that is by using Node.js [1].

Node.js is not just for big corporate projects. In fact, Node.js (or more specifically, the node executable supplied in Node.js installations) is, at its simplest, just a JavaScript interpreter. That's it. It lets you write scripts in JavaScript and then it runs them, just as you would run a Bash, Python, or Perl script.

For example, you can make the following code in Listing 1 executable (chmod a+x countdown.js) and run it from the command line.

Listing 1

countdown.js

@LI:01 #!/<path/to/bin>/node
02
03 for (i=10; i>0; i--)
04 {
05    console.log(i);
06 }
07 console.log("Booom!");

The big thing about Node.js is its ecosystem – that is, its community and all the stuff people have built around it. Thanks to the astonishing number of modules and tools developers have created, you can use Node.js for nearly everything, from multiplatform mobile apps, to customized specialized web servers, like the one I'll show you how to construct in this article. First, however, you need to get Node.js set up on your Rasp Pi.

Installing Node.js

Although the easiest way of getting Node.js onto your Rasp Pi is with the usual apt-get install procedure, the versions of node and npm in the Raspbian/Debian repositories are ancient and will bork if you try to install any modern modules (including the digital humidity and temperature module you will use here). My advice is to get the newer, stabler version from the Node.js project website [2].

When deciding which version to pick, the original Rasp Pi uses an ARMv6 processor, but the Raspberry Pi 2 (RPi2) and RPi3 use ARMv7 CPUs. If in doubt, you can check what version CPU your Rasp Pi has by running the following from the command line:

cat /proc/cpuinfo

I'm using an RPi3, which comes with an ARMv7 CPU onboard, so I'll grab the ARMv7 version:

wget https://nodejs.org/dist/v<X.X.X>/  node-v<X.X.X>-linux-armv7l.tar.xz

Where <X.X.X> is the version number.

You can then uncompress the file with:

tar xvf node-v<X.X.X>-linux-armv7l.tar.xz

The package comes with all its dependencies, so you don't need to install anything else. However, you do need to make sure that the Node.js bin/ directory is accessible from everywhere, so first rename your directory from node-v<X.X.X>-linux-armv7l to something simpler (e.g., nodejs):

mv node-v<X.X.X>-linux-armv7l nodejs

Then, include it into your PATH variable. Use your preferred text editor to open the .bashrc file, which lives in your /home/pi directory, and add the following line at the end:

export PATH=$PATH:/home/pi/<path/to>/nodejs/bin/

Save the file and exit your editor. Apply the changes with:

source .bashrc

From now on you will be able to access the Node.js tools from everywhere. For example, to try out the node console, type

node

in a terminal window, and you should see something that looks like Figure 1.

Figure 1: The Node shell allows you to try JavaScript commands.

If your JavaScript is a bit rusty, you can test your skills here and try running modules and extensions that Node.js incorporates into the language. To exit, press Ctrl+D.

When you are happy, you can use any text editor you like to write your own scripts and then use the node command to run them:

node yourscript.js

Or, you can make them executable and include a hashbang line (#!/<path/to/bin>/node), as shown in Listing 1, so that Bash knows which interpreter to use when it runs the script.

Your First Server

Where Node.js becomes really useful is when you use it to build a dedicated server. In this article, for example, you're going to see how to build a web server that reads input from a digital temperature and humidity (DHT) sensor (Figure 2) connected to your Rasp Pi and then serves the input up graphically on a web page.

Figure 2: The DHT sensor used in this project.

A basic template for a web server that serves up static chunks of text looks like Listing 2.

Listing 2

server_basic.js

01 var http = require("http");
02
03 http.createServer(function (request, response)
04 {
05   response.writeHead(200, {'Content-Type': 'text/html'});
06   response.write("<h1>Some</h1>");
07   response.write("<p>Formatted text.</p>");
08   response.end("<h2>The end</h2>" );
09 }).listen(8081);
10
11 console.log("Server running on port 8081");

Line 1 creates a new http object, which is the base for your web server. The require keyword is how you load a module into your script from Node.js. The http module comes as a standard part with all Node.js installations.

You create the server proper on line 3, which takes the shape of a callback function, or a function that is usually nameless and is passed as a parameter to another function. The createServer's callback function has two parameters: request is an object that manages the incoming messages sent by the users' web browsers. Every time you ask for a certain page through your browser, a request is sent to the web server. The response parameter, on the other hand, manages what the web server sends back to the user. The specific page (or if, for example, the page doesn't exist, a 404 error) is a response.

Line 5 tells the server the encoding of the response to be sent back in. In this case, you tell the server to serve back HTML-formatted text.

Line 6 starts sending the content. You can have as many response.write() lines as you want, and you can mix them with if, while, and other control statements. In this case, though, you just serve up static HTML and finish up with the response.end() call on line 8. Note that if you don't include a call to response.end(), your page will load forever.

Finally, createserver() has a listen() method (line 9), which you can use to set the port on which the server listens. Line 11 just prints out a reminder to the command line of the port on which your server is running.

Now you can run your server with:

node server_basic.js

Visit the IP of your Rasp Pi. In my case, my Rasp Pi can be found at 192.168.1.106 on my local network, so I visit http://192.168.1.106:8081. When the page loads, you'll see something like Figure 3.

Figure 3: Point your browser to your Raspberry Pi's IP on port 8081 to see the page sent by your server.

Buy this article as PDF

Express-Checkout as PDF

Pages: 8

Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content