Jaap : node, npm & grunt

  • 29,670 views
Uploaded on

JavaScript As A Platform: overview of node.js, npm and grunt given the 23/05/2013 at Yajug. …

JavaScript As A Platform: overview of node.js, npm and grunt given the 23/05/2013 at Yajug.

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
  • The full presentation with the video is available on parleys http://parleys.com/p/51d15d51e4b09706b381fab0
    Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
29,670
On Slideshare
0
From Embeds
0
Number of Embeds
2

Actions

Shares
Downloads
1
Comments
1
Likes
7

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. JavaScript as a Platform Node.js, NPM and Grunt
  • 2. About { "firstName" : "Bertrand", "lastName" : "Chevrier", "online" : { "twitter" : "@kramp", "github" : "github.com/krampstudio", "blog" : "krampstudio.com" }, "pro" : { "employer" : "CGI", "position" : "Technical expert" }, "loves" : ["JavaScript", "Linux", "Java", "PHP"] }
  • 3. JS, OSS & me
  • 4. Follow the dealer krampstudio.com github.com/krampstudio
  • 5. Why Node.js
  • 6. 1. Buzzword ? 2. JS.everywhere(2013); 3. JIFSNIF 4. Huge community Platform Repo Total packages Platform years old Avg/year since platform Repo years old Avg/year since repo Python PyPI 31 066 22 1 412 10 3 106 Java Maven central 58 272 18 3 237 9 6 474 Ruby Gems.org 56 869 18 3 159 5 11 373 Node Npm 30471 4 7617 3 10 157 stats polled the 21st of May 2013 JavaScript is fun so node is funnier
  • 7. WTF is node.js ? The illegitimate child of Google and Netscape !
  • 8. 2008, Ryan Dahl How to build scalable real-time web app with simplicity ?
  • 9. Architecture
  • 10. node.js isn't - A programming language - A web framework
  • 11. node.js is - A low level lib for I/O programming
  • 12. node.js design - Non blocking I/O - Event driven model - JavaScript - Unix philosophy
  • 13. Inspiration - Twisted (Python) - Tornado (Python) - EventMachine (Ruby) - libevent (C) - Nginx
  • 14. Non blocking I/O for scalability
  • 15. Cost of I/O I/O cycles L1-cache 3 L2-cache 14 RAM 250 Disk 41 000 000 Network 240 000 000 http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop
  • 16. Threaded server
  • 17. Non blocking server
  • 18. memory usage / concurrent connections
  • 19. request p. sec. / concurrent connections
  • 20. - Event driven model - Low levels I/O APIs rewritten - Fat process Node is designed to be non blocking from top to bottom.
  • 21. JavaScript for simplicity
  • 22. Why JS?
  • 23. The good parts for node - Functionnal language : fits the event model - Easily extensible : redesign of non blocking APIs, DSLable - Becomes popular : the language of the web
  • 24. Unix philosophy KISS & Battery not included
  • 25. Node provides only low level APIs Nothing superfluous.
  • 26. EcmaScript 5 + CommonJs + APIs: - Cluster, Child_Process and Process - Crypto - Module, Domain, Events, Timers - Assert, Utilities - File System, Path, OS, VM - HTTP, Net, URL, QueryString, etc. - Net, DNS, UDP - Buffer, Stream, STDIO, Readline, TTY - REPL nodejs.org/api
  • 27. JavaScript (ES5) file import ?
  • 28. Modules Require module.exports = { //your object }; var fs = require('fs');
  • 29. Diving into node
  • 30. Coding with node Discovering the patterns
  • 31. Required Hello Node.js world var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888); $ node hello_node_world.js
  • 32. Demo : node-htop
  • 33. Polling system stats
  • 34. Real time
  • 35. Callbacks, Errorbacks demo:lib/poller/mem.js#32 function async(data, callback) { if (!data) { callback(new Error('Empty data')); } //do something and then callback(null, true); }; async({data: 'test'}, function(err, valid){ console.log("finished"); });
  • 36. Callback tree demo:lib/poller/mem.js#32 http.createServer(function processRequest(request, response){ fs.exists("/tmp/test", function(exists){ if(exists === true){ fs.stat(file, function(err, stat){ fs.appendFile(file, log, 'utf8', function(err){ db.query(function(err, data){ //etc ... }); }); }); } }); }
  • 37. Async management demo:lib/statpoller.js#124 var async = require('async'); var fs = require('fs'); async.filter(['file1','file2','file3'], fs.exists, function(results){ //results => [true, false, true] }); function f1(cb){ fs.exists('dir1', function(result){ if(result === true){ cb(null, true); } else { cb(new Error('Oh crap!'); } }); } async.series([f1, f2], function(err, results){ // results => [true, true] or null });
  • 38. Futures and promises var q = require('q'), fs = require('fs'); var readFile = q.node(fs.readFile); readFile('test.txt').then(function (data) { console.log("finished"); }).then(function(){ console.log("do something else"); });
  • 39. Events demo:lib/statpoller.js#1 var events = require('events'); var Test = function(){ events.EventEmitter.call(this); }; util.inherits(Test, events.EventEmitter); Test.prototype.start = function(){ this.emit('started', { 'when' : new Date() }); }; var myTest = new Test(); myTest.on('started', function(data){ console.log("test started"); }); myTest.start();
  • 40. Middleware var app = { stack : [], use : function(middleware){ var fn = middleware; if('function' === typeof middleware.handle){ fn = middleware.handle; } if('function' === typeof fn){ this.stack.push(fn); } }, handle : function(data){ var i = 0, layer; for(i in this.stack){ layer = this.stack[i]; if(!layer(data)){ break; } } } };
  • 41. app.use(function(data){ console.log("Hello %s", data); return true; }); app.use(function(data){ console.error("Goodbye %s", data); return false; }); app.handle('middleware');
  • 42. Connect : HTTP middlewares demo:app.js#20 var app = connect() .use(connect.logger('dev')) .use(connect.static('public')) .use(function(req, res){ res.end('hello worldn'); }) .listen(3000);
  • 43. Errors try { //something that crash } catch(e) { console.error(e); }; function(cb){ if(error) cb(new Error("Sorry...")); } else { cb(null, theData); } }
  • 44. demo:lib/statpoller.js#63 myEmitter.on('error', function(e){ console.error(e.stack); }); var aDomain = domain.create(); aDomain.on('error', function(err){ //do wafyw with the err }); aDomain.run(function(){ //do some errorable stuffs (throws, errbacks, etc. are catched) });
  • 45. Scaling node.js But, wait, I've only one process...
  • 46. Scale Up Use your CPUs !
  • 47. Cluster demo:server.js var cluster = require('cluster'); var http = require('http'); var numCPUs = require('os').cpus().length; if (cluster.isMaster) { for (var i = 0; i > numCPUs; i++) { cluster.fork(); } cluster.on('exit', function(worker, code, signal) { //manage worker stop }); } else { //I'm in a fork }
  • 48. Scale out Load balance and share the events
  • 49. Node Package Manager
  • 50. NPM do : packages as CommonJS modules
  • 51. How ? - Simple CLI tools - Registry - Web site - Included in node.js since 0.6 - Git friendly $ npm --help registry.npmjs.org npmjs.org
  • 52. Module Metas package.json { "name": "node-htop", "version": "0.1.0", "description": "Web htop like", "main": "app.js", "scripts": { "test": "grunt test" }, "dependencies": { "express": "3.2.x", "socket.io": "0.9.x", "underscore": "~1.4.0" } } demo package.json
  • 53. Usage $ npm search bower $ npm info bower $ npm install -g bower $ npm install --save socket.io $ npm update $ npm publish
  • 54. Scopes global -> user -> project
  • 55. Transitive dependencies A-0.1 -> B-0.1, C-0.1 B-01 -> C-0.2 A-0.1 ├── node_modules │ ├── B-0.1 │ │ └── node_modules │ │ └── C-0.2 │ └── C-0.1 └── package.json
  • 56. npm is not capable of hatred. It loves everyone, especially you. source Why does npm hate me? npm faq
  • 57. Node.js is fun but...
  • 58. Defects - Young project - Libraries hell - Error management - Monoculture - Noob friendly - Devops required
  • 59. Node is a cancer Ted Dzubia
  • 60. Coffescript invokes the : JavaScript is a Toy!
  • 61. beard theory
  • 62. Uncle Ben, Spiderman With great power, comes great responsibility
  • 63. Grunt, the task runner
  • 64. Automate your projects - Task based - By configuration Gruntfile.js - NPM friendly - Extensible by nature
  • 65. Let's do some Grrrrunt
  • 66. Why Grunt? - Wide numbers of plugins - Simple to use - Easy to customize - 0.5 : will use the node-taskformat
  • 67. Grunt in your stack =
  • 68. Merci
  • 69. Play at home demo source slide decks