Introduction to node.js
- 5. keywords
easy
fast development
scalable
event-driven
non-blocking I/O model (single thread!)
- 6. event-driven & non-blocking I/O
Avoid long calculations and synchronuous calls
sensor.on(“data”, function(data){
// do something with the data
});
// code belows continues to be executed
- 7. Used by
IBM
Walmart
Yahoo
LinkedIn
PayPal
Mozilla
Worldline e-payment services and many more
- 10. Variables & types
var name = “Steven Beeckman”;
var age = 30;
var alive = true;
var length_in_meters = 1.98;
length_in_meters = “N/A”;
console.log(typeof length_in_meters);
- 11. Variables & types
var addresses = new Array();
var main_address = new Object();
main_address.street = “Wolvertemsestwg”;
main_address.postalcode = 1785;
main_address.type = “Main Address”;
main_address.dropPost = new function(package){...};
addresses.push(main_address);
console.dir(addresses);
- 12. Operators
var x = 4;
x = x + 1; // x is 5
y = x % 2; // y is 1
x++; // x is 6
x--; // x is 5
x += 3; // x is 8
var aString = "The value of x is " + x;
- 14. Flow control
if (x > 0) {
// do something
} else {
// do something else
}
x == 5 ? doWhenFive() : doWhenNotFive();
- 15. Loops
for (var i = 0; i < myArray.length; i++) {
console.dir(myArray[i]);
}
while (x < 10) {
console.log(x++);
}
- 16. Functions
function myIncrementFunction (x) {
return x + 1;
}
var result = myIncrementFunction(5); // 6
// functions are first class citizens in JS
var inc = new function(x){ return x+1;}
result = inc(7); // 8
- 17. Packages - NPM
Node Package Manager - http://npmjs.org
Command-line tool
npm install --save express
--save adds package automatically as a
dependency in your package.json file
-g installs the package globally
- 19. Handling events
var five = require(“johnny-five”);
var myBoard = new five.Board();
myBoard.on("ready", function() {
// code to be executed when the
board is ready
});
- 20. MEAN stack
MongoDB (NoSQL document store)
Express.js (~Sinatra of Ruby on Rails)
Angular.js (Google’s front-end JS framework)
Node.js (duh)
- 21. Sockets
Real-time push with socket.io
var io = require('socket.io')(80);
var cfg = require('./config.json');
var tw = require('node-tweet-stream')(cfg);
tw.track('socket.io');
tw.track('javascript');
tw.on('tweet', function(tweet){
io.emit('tweet', tweet);
});
- 22. Sockets
Real-time push with socket.io
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
io.on('connection', function(socket){
console.log('a user connected');
socket.on('tweet', function(){
console.log(tweet);
});
});
- 26. References
http://nodejs.org
http://expressjs.com
http://nodeschool.io
http://www.meetup.com/Belgian-node-js-User-Group/
http://node-ardx.org/js-primer
https://www.npmjs.org/
http://www.heroku.com
http://www.digitalocean.com
http://www.nodejitsu.com
http://www.mongodb.com