In this article I want to describe how to set up a Nodejs environment on your Raspberry Pi.
A basic setup of Raspbian on a Raspberry is clearly explained in my last article Raspberry Pi A+, First 10 minutes

Connect to the Raspberry Pi

###default user pi (change with your user)
ssh pi@[RaspIP]   
#update...
sudo apt-get update
### you don't know ip?? find it with nmap   
###if your IP address is 192.168.1.XXX.
sudo nmap -sP 192.168.1.0/24`

Install Nodejs

#download and install..simple!  
wget http://node-arm.herokuapp.com/node_latest_armhf.deb 
sudo dpkg -i node_latest_armhf.deb
#to check your installation..
node -v

Install SQLite

I'm going to use SQLite in this tutorial because it's compact,and easy to use. Unlike MySQL, no server process is needed to access an SQLite database.

    #install sqlite
    sudo apt-get install sqlite3   

To chek installation write sqlite3 into shell...

sqlite3 shell

For details: SQLite3 documentation

DEMO1: Hello Node

Now is time to write hello node...

 #create a simple hello.js and launche with node
cd /var/www
sudo nano hellonode.js
 #put the code into a file hellonode.js 
/*
     var http = require('http');
     http.createServer(function (req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello node\n');
     }).listen(1337, '127.0.0.1');
     console.log('Server running on port 1337');
 */
#execute it with the node 
node /var/www/hellonode.js

alt

DEMO2: HELLO SQLITE

In this example i want to use sqlite from ultra simple node script.

Install sqlite3 module for Node.js

npm install sqlite3
#(local installation...)

create a simple sqlitehello.js and launche with node

  var sqlite3 = require('sqlite3').verbose();
  var db = new sqlite3.Database('sqlitehello.db');
  var check;
  db.serialize(function() {

    db.run("CREATE TABLE if not exists hello (info TEXT)");
    var stmt = db.prepare("INSERT INTO hello VALUES (?)");
    for (var i = 0; i < 5; i++) {
        stmt.run("hello sqlite" + i);
    }
    stmt.finalize();

    db.each("SELECT rowid AS id, info FROM hello", function(err, row) {
        console.log("id:"+row.id + " text: " + row.info);
    });
  });

  db.close();

sqlite demo

The Data are stored into the file: sqlitehello.db

© 2018. All Rights Reserved.

Ghostium Theme by @oswaldoacauan

published with Ghost

Privacy Policy