Installing Node on the Pi
- sudo apt-get update (Update the Operating System)
- curl -sL https://deb.nodesource.com/setup | sudo bash - (Setup node repo source)
- sudo apt-get install nodejs (Install node)
- 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…