aka:JavaScript:Node.js
This memo uses a part of the table of content of the book 'Node.js in Action.' But the content of memo is basically my original.
- Node Programming Fundamentals
- Organizaing and reusing Node functionality
- Node has a module system which allows you to organise and reuse your code.
- Node modules don't pollute the global name space.
- The properties of the module.exports object in your module will be exposed to a module user through the object the require returns.
- Ex: piyo.js (piyo module )
module.exports.hoge = function () { return 'puyo'; }
- user.js (user of piyo module)
require('./piyo.js').hoge(); // => 'puyo'
- Ex: piyo.js (piyo module )
- A Node module can be a file or a directory containing file(s).
- Administrative features such as module lookup on file systems or package description through package.json is available. For the detail, see the node.js spec.
- Node has a module system which allows you to organise and reuse your code.
- Asynchronous programming techniques
- Node brings the asynchronous way of writing programs on web browsers into server side.
- Callbacks, or CPS, and event listeners are central devices to achieve that.
- Node implements a core class called Event Emitter, which you can use to create event-driven programs. Ex. A Node HTTP server.
- Most Node built-in functions use callbacks with two arguments: an error and the results.
var fs = require('fs'); fs.readFile('./hoge.txt', function(error, data) { // ... }
- You can use Node's event emitter facilities by inheriting the EventEmitter class.
var events = require('events'); var channel = new events.EventEmitter();
- Here is a list of EventEmitter APIs.
- emitter.addListener(event, listener)
- emitter.on(event, listener)
- emitter.once(event, listener)
- emitter.removeListener(event, listener)
- emitter.removeAllListeners([event])
- emitter.setMaxListeners(n)
- emitter.listeners(event)
- emitter.emit(event, [arg1], [arg2], [...]) --Sequencing asynchronous logic
- emitter.addListener(event, listener)
- There are two flow control patterns to orchestrate asynchronous tasks: serial and parallel.
- Serial: executes multiple tasks sequentially.
- Parallel: executes multiple tasks in parallel but proceed to next step after all the tasks were finished.
- A typical way to implement a serial flow control is to create a helper function called next() and use it at the end of each task when it need to pass its result to the next task:
var tasks = { task1, task2 } function next(error, result) { if (error) throw error; var currentTask = tasks.shift(); if (currentTask) { currentTask(result); } next(); } function task1 () { next(null, 'hoge'); } function task2 (secret) { next(null, secret + 'piyo'); }
- Here is an example implementation of parallel flow control:
var completedTasks = 0; var tasks = []; function checkIfComplete() { completedTasks++; if (completedTasks == tasks.length) { // do something } }
- Organizaing and reusing Node functionality