Node.js

Description
Node.js est un canevas événementiel pour réaliser des applications serveur en Javascript. L'ensemble des événements est traité par une seule thread: Node.js privilégie les appels non bloquants. Node.js facilite le push (serveur --> client Web)

Cours
 * Formation Valtech : http://public.valtech-training.fr/DekNOD/slideshow/dist/#1

Lancement
Aide node --help

Interactif node

En ligne node -p -e "Boolean(process.stdout.isTTY)"

En argument (process.argv[1]) node httpserver.js 8080

API
Des nombreuses bibliothèques sont disponibles : Assertion Testing, Buffer, C/C++ Addons, Child Processes, Cluster, Crypto, Debugger, DNS, Domain, Events, File System, Globals, HTTP, HTTPS, Modules, Net, OS, Path, Process, Punycode, Query Strings, Readline, REPL, STDIO, Stream, String Decoder, Timers, TLS/SSL, TTY, UDP/Datagram, URL, Utilities, VM, ZLIB

Canevas
Des nombreux canevas sont construits sur Node.js
 * ql.io

Registre
Plusieurs modules sont catalogués depuis le registre https://npmjs.org/ et installables avec npm (Node Package Manager)

npm ls
 * 1) Voir les packages disponibles

npm ls installed
 * 1) Voir les packages installés

npm search duino
 * 1) Rechercher un package

npm install duino
 * 1) Installer un package pour le contrôle d'une carte Arduino

npm publish mypackage
 * 1) Installer un package

Modules pour les projets AIR

 * node-serialport access serial ports for reading and writing
 * duino A framework for working with Arduinos in node.js
 * firmata A Node library to interact with an Arduino running the firmata protocol.

Lancement
Aide node --help

Interactif node

En ligne node -p -e "Boolean(process.stdout.isTTY)"

En argument (process.argv[1]) node httpserver.js 8080

HTTP script
var port = process.argv[2];

var http = require("http");

function onRequest(request, response) { console.log("Receiving a request"); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end; }

http.createServer(onRequest).listen(port); console.log("Server started. ^C to kill it");

node hello.js 8888

Express
var express = require('express'); var app = express; app.get('/hello.txt', function(req, res){ res.send('Hello World'); }); app.listen(3000);

node install express node express.js 3000

start http://localhost:3000/hello.txt

UDP Datagrams
var dgram = require("dgram");

var server = dgram.createSocket("udp4");

server.on("message", function (msg, rinfo) { console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port); });

server.on("listening", function {  var address = server.address;  console.log("server listening " + address.address + ":" + address.port); });

server.bind(41234); // server listening 0.0.0.0:41234

node dgram.js

Crypto: SHA1 Hashing
var filename = process.argv[2]; var crypto = require('crypto'); var fs = require('fs');

var shasum = crypto.createHash('sha1');

var s = fs.ReadStream(filename); s.on('data', function(d) { shasum.update(d); });

s.on('end', function { var d = shasum.digest('hex');  console.log(d + '  ' + filename); });

node hash.js hash.js

TTY
process.stdout.on('resize', function { console.log('screen size has changed!');  console.log(process.stdout.columns + 'x' + process.stdout.rows); });

node resize.js

$ node -p -e "Boolean(process.stdout.isTTY)" true $ node -p -e "Boolean(process.stdout.isTTY)" | cat false

Cluster
var port = process.argv[2]; var cluster = require('cluster'); var http = require('http'); var numCPUs = require('os').cpus.length;

if (cluster.isMaster) { // Fork workers. for (var i = 0; i < numCPUs; i++) { cluster.fork; }

cluster.on('exit', function(worker, code, signal) {   console.log('worker ' + worker.process.pid + ' died');  }); } else { // Workers can share any TCP connection // In this case its a HTTP server http.createServer(function(req, res) {   res.writeHead(200);    res.end("hello world\n");  }).listen(port); }

node httpcluster.js 8080

Serial GPS
var SerialPort = require("serialport").SerialPort; var util = require("util"), repl = require("repl");

var port = process.argv[2]; var baudrate = process.argv[3];

if (!port) { console.log("You must specify a serial port location of your NMEA GPS receiver."); } else { if (!baudrate) { baudrate = 4800; }

var serial_port = new SerialPort(port, {baudrate: baudrate}); serial_port.on("data", function (data) {   util.puts("data: "+data);  }) serial_port.on("error", function (msg) {   util.puts("error: "+msg);  }) repl.start("=>") //serial_port.close; }

npm install serialport node serialgps.js

NMEA 0183 Parsing
var nmea = require('nmea')

var s = [ "$GPGSA,A,1,,,,,,,,,,,,,,,*1E", "$GPGSV,3,1,12,29,75,266,39,05,48,047,,26,43,108,,15,35,157,*78", "$GPGSV,3,2,12,21,30,292,,18,21,234,,02,18,093,,25,13,215,*7F", "$GPGSV,3,3,12,30,11,308,,16,,333,,12,,191,,07,-4,033,*62", "$GPRMC,085542.023,V,,,,,,,041211,,,N*45", "$GPGGA,085543.023,,,,,0,00,,,M,0.0,M,,0000*58", ];

for (var i=0; i < s.length; i++) { console.log(nmea.parse(s[i])); };

npm install testnmea node testnmea.js

see also https://npmjs.org/package/coordinator

Simple Arduino Test
// arduino-ldr-read.ino from https://github.com/voodootikigod/node-serialport/blob/master/tests/arduino-ldr-read.pde int sensorPin = A0;   // select the input pin for the potentiometer int ledPin = 13;     // select the pin for the LED int sensorValue = 0; // variable to store the value coming from the sensor

void setup { pinMode(ledPin, OUTPUT); Serial.begin(9600); }

void loop { sensorValue = analogRead(sensorPin); Serial.println(sensorValue); digitalWrite(ledPin, HIGH); delay(sensorValue); digitalWrite(ledPin, LOW); delay(sensorValue); }

// From https://github.com/voodootikigod/node-serialport/blob/master/tests/arduino-ldr-read.js // For use with Arduino LDR // Upload arduino-ldr-read.ino to Arduino apparatus via Arduino IDE

var port = process.argv[2];

var sys = require("sys"), repl = require("repl"), serialPort = require("serialport").SerialPort,

//	Required defaults = { baudrate: 9600 },		//	Create new serialport pointer serial = new serialPort(port, defaults);

//	Add data read event listener serial.on( "data", function( data ) {

var output;

//	Coerce data into a number data = +data;

//	If data is worth reading and processing if ( data && data > 1 ) {

//	Create a new Array whose length equals data //	then join to create output visualization output = ( new Array(data) ).join( ">" );

//	Print the data value along with visualization of data sys.puts( data + " " + output ); }

});

serial.on( "error", function( msg ) {	sys.puts("error: " + msg ); });

repl.start( "=>" );

npm install serialport node arduino-ldr-read.js /dev/ttyACM0

NFC RFID Readers
See:
 * https://npmjs.org/package/node-hid
 * http://svay.com/blog/hacking-rfid-with-nodejs/

var HID = require('node-hid'); console.log(HID.devices);

npm install node-hid node listhid.js