This page will shows on how to use NodeJS to program and create a web page through Raspberry Pi. Have a look !!!.
Credit to this website:
https://www.w3schools.com/nodejs/nodejs_raspberrypi.asp
Install Node.js on Raspberry Pi
Before install the Node.js, it is recommended to update the package of Rapsberry pi system to their latest version. Type the command below:
sudo apt-get update
Then, upgrade all your installed packages to their latest version:
sudo apt-get dist-upgrade
To download and install newest version of Node.js, use the following command:pi@w3demopi:~ $
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash –
Now install it by running:
sudo apt-get install -y nodejs
Check that the installation was successful, and the version number of Node.js with:
node -v
Install the onoff Module
To interface with the GPIO on the Raspberry Pi using Node.js, we will use a Module called “onoff”.
Install the onoff module using npm:
npm install onoff
Now onoff should be installed and we can interact with the GPIO of the Raspberry Pi.
Node.js Blinking LED Script
In order to write a script to blink the LED on and off, you need to create a new js file using nano editor. Let name it as “blink.js”. Example:
sudo nano /home/pi/Desktop/Mobile_App/NodeJS/blink.js
The file is now open and can be edited with the built in Nano Editor.
Write, or paste the following code:
##——————————————————————————————————-##
var Gpio = require(‘onoff’).Gpio; //include onoff to interact with the GPIO
var LED = new Gpio(4, ‘out’); //use GPIO pin 4, and specify that it is output
var blinkInterval = setInterval(blinkLED, 250); //run the blinkLED function every 250ms
function blinkLED() { //function to start blinking
if (LED.readSync() === 0) { //check the pin state, if the state is 0 (or off)
LED.writeSync(1); //set pin state to 1 (turn LED on)
} else {
LED.writeSync(0); //set pin state to 0 (turn LED off)
}
}
function endBlink() { //function to stop blinking
clearInterval(blinkInterval); // Stop blink intervals
LED.writeSync(0); // Turn LED off
LED.unexport(); // Unexport GPIO to free resources
}
setTimeout(endBlink, 5000); //stop blinking after 5 seconds
##——————————————————————————————————-##
Press “Ctrl+x
” to save the code. Confirm with “y
“, and confirm the name with “Enter
“.
Run the code:
sudo node blink.js
Now the LED should blink for 5 seconds (10 times) before turning off again!