Node.js: Difference between revisions
No edit summary |
|||
| Line 268: | Line 268: | ||
<pre> |
<pre> |
||
node httpcluster.js 8080 |
node httpcluster.js 8080 |
||
</pre> |
|||
===Serial GPS=== |
|||
<pre> |
|||
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(); |
|||
} |
|||
</pre> |
|||
<pre> |
|||
npm install serialport |
|||
node serialgps.js |
|||
</pre> |
|||
===Simple Arduino Test=== |
|||
<pre> |
|||
// 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); |
|||
} |
|||
</pre> |
|||
<pre> |
|||
// 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( "=>" ); |
|||
</pre> |
|||
<pre> |
|||
npm install serialport |
|||
node arduino-ldr-read.js /dev/ttyACM0 |
|||
</pre> |
</pre> |
||
Revision as of 11:48, 3 March 2013
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)
# Voir les packages disponibles npm ls # Voir les packages installés npm ls installed # Rechercher un package npm search duino # Installer un package pour le contrôle d'une carte Arduino npm install duino # Installer un package npm publish mypackage
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.
Exemples
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
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