Challenge
So we want to run a simple http server that will start running when the Raspberry Pi starts up?
Install node.js on Pi
wget http://node-arm.herokuapp.com/node_latest_armhf.deb sudo dpkg -i node_latest_armhf.deb
Test:
On your Pi create a folder called ~/nodejs.
Create a file called https.js on Mac with the following:
node --version
On your Pi create a folder called ~/nodejs.
Create a file called https.js on Mac with the following:
var http = require('http');
var number = 0;
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var num = number.toString();
res.end('Hello World ' + num + '\n' );
}).listen(1337, 'xxx.x.x.x');
var interval = setInterval(function(){
number++;
},2000);
console.log('Server running at http://xxx.x.x.x:1337/');
where xxx.x.x.x is the IP address of your Raspberry Pi. This server will increment a number every 2 seconds indefinitely and publish it.
Copy the file https.js to Pi's ~/nodejs folder as follows:
scp ./https.js pi@raspberrypi:~/nodejs
..or..
scp ./https.js pi@xxx.x.x.x:~/nodejs
On your pi edit the file /etc/rc.local. Add the following line:
su pi -c 'node /home/pi/nodejs/https.js'
This will run the node command at startup as the user pi (who installed node.js).
This way your http server will start running as soon as your Pi restarts.
To test on a browser
http://xxx.x.x.x:1337/
This will show a page as follows. The number will increment by one at each refresh at 2 second interval.
Hello World 905
Thanks to Pieter Beulque's tips here.
No comments :
Post a Comment