12. First node.js server var http = require ( 'http' ); http. createServer ( function (req, res) { res. writeHead ( 200 , { 'Content-type' : 'text/plain' }); res. end ( 'Hello world!' ); }). listen ( 1337 ); console. log ( 'Server running at http://localhost:1337' );
13.
14.
15. Packaged modules $ curl http://npmjs.org/install.sh | sh $ npm install db-mysql There are more than 3350 packages, and more than 14 are added each day
16. Packaged modules var m = require ( './module' ); m. sum ( 1 , 3 , function (err, res) { if (err) { return console. log ( 'ERROR: ' + err); } console. log ( 'RESULT IS: ' + res); }); exports.sum = function (a, b, callback) { if ( isNaN (a) || isNaN (b)) { return callback ( new Error ( 'Invalid parameter' )); } callback ( null , a+b); };
17.
18. Multiple environments var express = require ( 'express' ); var app = express. createServer (); app. get ( '/' , function (req, res) { res. send ( 'Hello world!' ); }); app. listen ( 3000 ); console. log ( 'Server listening in http://localhost:3000' ); app. configure ( function () { app. use (express. bodyParser ()); }); app. configure ( 'dev' , function () { app. use (express. logger ()); }); $ NODE_ENV=dev node app.js
19. Middleware function getUser (req, res, next) { if (!req.params.id) { return next (); } else if (!users[req.params.id]) { return next ( new Error ( 'Invalid user' )); } req.user = users[req.params.id]; next (); } app. get ( '/users/:id?' , getUser, function (req, res, next) { if (!req.user) { return next (); } res. send (req.user); });
20.
21.
22. node-db var mysql = require ( 'db-mysql' ); new mysql. Database ({ hostname: 'localhost' , user: 'root' , password: 'password' , database: 'db' }). connect ( function (err) { if (err) { return console. log ( 'CONNECT error: ' , err); } this . query (). select ([ 'id' , 'email' ]). from ( 'users' ). where ( 'approved = ? AND role IN ?' , [ true , [ 'user' , 'admin' ] ]). execute ( function (err, rows, cols) { if (err) { return console. log ( 'QUERY error: ' , err); } console. log (rows, cols); }); });
** NORMALLY DOING: It's waiting. You get a request, query the DB, and wait for results. You write to a file, and wait for it to be written. You encode a video, and wait for it to complete. ** CACHING: File caching, Memcached ** WORKERS: Use robot plugin, or Gearman, or ActiveMQ / RabbitMQ ** FASTER DB: NoSQL (MongoDB, CouchDB)
You can't simply spawn a new process or thread for each connection NGINX is event based, so memory usage is low APACHE spawns a thread per request (or process depending on configuration) THREADS spend a lot of time being blocked waiting for I/O operations EVENTS are better when more time is spent waiting on external resources
** V8: Without DOM parts
** PROPERTIES: Object properties can be changed at runtime in JS: property dictionaries Instance variables have fixed offsetts set by compiler. V8 creates hidden classes, one for each property added and class transitions show changes to object properties (only first time) ** MACHINE CODE: when first executed JS is compiled into machine code, no intermediate byte code ** GARBAGE: when running GC, program stops. Each GC cycle only process part of the heap.
** LIBEIO: by Marc Lehmann. Can be used with any event library, or in POLLING mode. Relies only on POSIX threads. Uses threads internally, and used by Node.JS for file/network access, integrated in node to LIBEV ** LIBEV: also by Marc Lehmann. asynchronous notification of file descriptor changes through ev_io() ** ReadFile(): lots of JS code, on top of fs.open(), which is a wrapper around C++ Open(), which uses libeio
Node on Windows is not loosing significant performance compared to Linux
** BUFFER: Outside of V8 heap. Conversion to JS through encoding (binary, utf8, ascii, etc.) ** C-ARES: gethostbyname(), custom DNS queries ** CHILD_PROCESSES: fork() is in JS land, special case of spawn(), with IPC messaging capabilities ** CRYPTO: create hashes, ciphers with different algorithms, signs with private keys, and verify signatures ** HTTP_PARSER: NO allocation, NO buffer ** TIMER: setTimeout() is one time, setInterval() is repeated
** SINGLE THREAD: Since node runs in a single thread, anything blocking that thread blocks node from processing other requests ** YOUR code: if your code uses I/O, that I/O is NON blocking ** I/O calls are the point at which Node.js switches between different requests. So Node.js expects requests to be done very fast. Intensive CPU should be done in another process
Since Node.JS runs in a single process, its bound to a single CPU ** OS approach: the kernel load balances connections across processes ** CLUSTER: uses several workers (in different CPUs), we will cover this later
** PACKAGES can be installed locally or globally
** COMMONJS: defines JS APIs for any purpose, such as server side JS. Amongst the things it defines, are modules ** The EXPORTS object is created by the module system. If you want your module to be a class, assign the export object to MODULE.EXPORTS
** ENVIRONMENTS: Can specify different middleware for each environment, and change settings ** MIDDLEWARE: for manipulating all requests, or for specific routes ** ROUTING: Including support for HTTP methods ** VIEW RENDERING: with different template engines, and including partials (sort of like CakePHP elements) ** SESSION SUPPORT: part of Connect, can be configured even with Redis
** MIDDLEWARES: order is important. ** BodyParser() allows the parsing of forms (including JSON posted data as part of body) ** Other middlewares include: cookieParser(), session()
With route middleware, it's easy to add authentication
** JADE is one of the view engines available: $ npm install jade
** CakePHP APP: including the use Auth with Form authentication ** JSON endpoint first in CakePHP, then in Node.js An alternative to the JSON endpoint is to use WEB SOCKETS, which offers a bi-directional communication channel over TCP. Its API is still being standarized by the W3C. The Node.JS module SOCKET.IO has great support for web sockets, and its client code works on almost every browser
** SIEGE: 25 concurrent users, 10 repetitions, 1 random secs delay ** NODE.JS: Using EXPRESS
** Even if you don't add CONSTRAINTS, always REMEMBER to add a KEY for each field that is to be used as foreign keys
** writeHead(statusCode, headersObject) ** ACCESS CONTROL: a wildcard, or an URI ** res.send(): automatically converts object to JSON string
** We are now doing a whole bunch of HTTP requests, which is not optimal, we need to reduce them to the bare minimum ** LONG polling: when a response is obtained, we schedule a new request ** CODE: when error, ALSO schedule a new request
** Allows prioritization in the queue ** Can handle idle timeouts (time a resource can go unused before it is destroyed)
** CLUSTER: can be extended via plugins. Spawns one worker per CPU. Handles signals and different types of shutdown. Can resucitate workers.
** COLLECTIONS: forEach, map, filter, and others ** SERIES(): runs in order, stops if one fails (error first arg). Calls final callback once they are all done (or ERRORED), with an array of all arguments sent to each task ** PARALLEL(): similar to SERIES(), does not stop on error ** WATERFALL(): like SERIES(), but each task pass its result as an argument to the next task
** EXPORT: create a module and define the test groups as elements of the module ** EXPECT(): specify how many assertions are expected to run in a test ** DONE(): ALL TESTS should call this. Marks the test as done