Sunday, December 27, 2015

Node on Raspberry Pi 2


Installing Node on the Pi

Open the Pi terminal and type the below commands. Make sure node is not installed already and your Raspberry Pi 2 is already setup and ready for installation.
  1. sudo apt-get update       (Update the Operating System)
  2. curl -sL https://deb.nodesource.com/setup | sudo bash -      (Setup node repo source)
  3. sudo apt-get install nodejs      (Install node)
  4. node  -v  or npm –version   (Verify node is installed correctly)

Create your first Node web app on the Pi

Create a new folder under /home/pi  named “nodeapps” and create a new file “app.js” in this folder.
  • nano app.js
  • Add the following code in file and save it:
    var http = require('http');
    var server = http.createServer(function (request, response) {
      response.writeHead(200, {"Content-Type": "text/plain"});
      response.end("Look ma I am running Node on my Raspberry Pi !\n");
    });
    server.listen(8080);
    console.log("Server running at http://127.0.0.1:8080/");
  • node app.js
  • Visit “http://127.0.0.1:8080” or “http://localhost:8080” in the Pi browser to see the app working. If your Raspberry Pi is connected with your network you can also view the app using the Pi’s IP Address and the port 8080.
  • Use Ctrl + C to terminate the node app.

If your terminate the node app incorrectly you might get the ‘EADDRINUSE’ error message next time cause the port 8080 will still be in use.
To resolve this you can either check for the listening event or kill all the node processes as answered
here.

Enjoy JavaScripting on Raspberry Pi…

 

AddIn