Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 780 lines (539 sloc) 35.088 kb
2a420a7 @tj No longer gitignoring html
tj authored
1 <html>
2 <head>
3 <title>Mastering Node</title>
4 <style>
5 body {
69df60f @tj Added crappy default theme
tj authored
6 font: 14px/1.4 "Lucida Grande", "Helvetica Neue", Arial, sans-serif;
2a420a7 @tj No longer gitignoring html
tj authored
7 padding: 50px 180px;
8 }
69df60f @tj Added crappy default theme
tj authored
9 h1 {
10 padding-left: 5px;
11 border-bottom: 3px solid #eee;
12 }
13 pre {
14 margin: 15px 0;
15 padding: 15px;
16 border: 1px solid #eee;
17 }
18 a {
19 color: #00aaff;
20 }
2a420a7 @tj No longer gitignoring html
tj authored
21 </style><div class='mp'>
22 <h1>Mastering Node</h1>
23 <p><a href="http://nodejs.org/">Node</a> is an exciting new platform developed by <em>Ryan Dahl</em>, allowing JavaScript developers to create extremely high performance servers by leveraging <a href="http://code.google.com/p/v8/">Google's V8</a> JavaScript engine, and asynchronous I/O. In <em>Mastering Node</em> we will discover how to write high concurrency web servers, utilizing the CommonJS module system, node's core libraries, third party modules, high level web development and more.</p>
24
25 </div>
26 <div class='mp'>
27 <h1>Installing Node</h1>
28 <p>In this chapter we will be looking at the installation and compilation of node. Although there are several ways we may install node, we will be looking at <a href="http://github.com/mxcl/homebrew">homebrew</a>, <a href="http://github.com/visionmedia/ndistro">nDistro</a>, and the most flexible method of course, compiling from source.</p>
29
30 <h3 id="Homebrew">Homebrew</h3>
31
32 <p>Homebrew is a package management system for <em>OSX</em> written in Ruby, is extremely well adopted, and easy to use. To install node via the <code>brew</code> executable simply run:</p>
33
34 <pre><code>$ brew install node.js
35 </code></pre>
36
37 <h2 id="nDistro">nDistro</h2>
38
39 <p><a href="http://github.com/visionmedia/ndistro">nDistro</a> is a distribution toolkit for node, which allows creation and installation of node distros within seconds. An <em>nDistro</em> is simply a dotfile named <em>.ndistro</em> which defines
40 module and node binary version dependencies. In the example
41 below we specify the node binary version <em>0.1.102</em>, as well as
42 several 3rd party modules.</p>
43
44 <pre><code>node 0.1.102
45 module senchalabs connect
46 module visionmedia express 1.0.0beta2
47 module visionmedia connect-form
48 module visionmedia connect-redis
49 module visionmedia jade
50 module visionmedia ejs
51 </code></pre>
52
53 <p>Any machine that can run a shell script can install distributions, and keeps dependencies defined to a single directory structure, making it easy to maintain an deploy. nDistro uses <a href="http://github.com/visionmedia/nodes">pre-compiled node binaries</a> making them extremely fast to install, and module tarballs which are fetched from <a href="http://github.com">GitHub</a> via <em>wget</em> or <em>curl</em> (auto detected).</p>
54
55 <p>To get started we first need to install nDistro itself, below we <em>cd</em> to our bin directory of choice, <em>curl</em> the shell script, and pipe the response to <em>sh</em> which will install nDistro to the current directory:</p>
56
57 <pre><code>$ cd /usr/local/bin &amp;&amp; curl http://github.com/visionmedia/ndistro/raw/master/install | sh
58 </code></pre>
59
60 <p>Next we can place the contents of our example in <em>./.ndistro</em>, and execute <em>ndistro</em> with no arguments, prompting the program to load the config, and start installing:</p>
61
62 <pre><code>$ ndistro
63 </code></pre>
64
65 <p>Installation of the example took less than 17 seconds on my machine, and outputs the following <em>stdout</em> indicating success, not bad for an entire stack!</p>
66
67 <pre><code>... installing node-0.1.102-i386
68 ... installing connect
69 ... installing express 1.0.0beta2
70 ... installing bin/express
71 ... installing connect-form
72 ... installing connect-redis
73 ... installing jade
74 ... installing bin/jade
75 ... installing ejs
76 ... installation complete
77 </code></pre>
78
79 <h2 id="Building-From-Source">Building From Source</h2>
80
81 <p>To build and install node from source, we first need to obtain the code. The first method of doing so is
82 via <code>git</code>, if you have git installed you can execute:</p>
83
84 <pre><code>$ git clone http://github.com/ry/node.git &amp;&amp; cd node
85 </code></pre>
86
87 <p>For those without <em>git</em>, or who prefer not to use it, we can also download the source via <em>curl</em>, <em>wget</em>, or similar:</p>
88
89 <pre><code>$ curl -# http://nodejs.org/dist/node-v0.1.99.tar.gz &gt; node.tar.gz
90 $ tar -zxf node.tar.gz
91 </code></pre>
92
93 <p>Now that we have the source on our machine, we can run <code>./configure</code> which discovers which libraries are available for node to utilize such as <em>OpenSSL</em> for transport security support, C and C++ compilers, etc. <code>make</code> which builds node, and finally <code>make install</code> which will install node.</p>
94
95 <pre><code>$ ./configure &amp;&amp; make &amp;&amp; make install
96 </code></pre>
97
98 </div>
99 <div class='mp'>
100 <h1>CommonJS Module System</h1>
101 <p><a href="http://commonjs.org">CommonJS</a> is a community driven effort to standardize packaging of JavaScript libraries, known as <em>modules</em>. Modules written which comply to this standard provide portability between other compliant frameworks such as narwhal, and in some cases even browsers.</p>
102
103 <p>Although this is ideal, in practice modules are often not portable due to relying on apis that are currently only provided by, or are tailored to node specifically. As the framework matures, and additional standards emerge our modules will become more portable.</p>
104
105 <h2 id="Creating-Modules">Creating Modules</h2>
106
107 <p>Lets create a utility module named <em>utils</em>, which will contain a <code>merge()</code> function to copy the properties of one object to another. Typically in a browser, or environment without CommonJS module support, this may look similar to below, where <code>utils</code> is a global variable.</p>
108
109 <pre><code>var utils = {};
110 utils.merge = function(obj, other) {};
111 </code></pre>
112
113 <p>Although namespacing can lower the chance of collisions, it can still become an issue, and when further namespacing is applied it can look flat-out silly. CommonJS modules aid in removing this issue by "wrapping" the contents of a JavaScript file with a closure similar to what is shown below, however more pseudo globals are available to the module in addition to <code>exports</code>, <code>require</code>, and <code>module</code>. The <code>exports</code> object is then returned when a user invokes <code>require('utils')</code>.</p>
114
115 <pre><code>var module = { exports: {}};
116 (function(module, exports){
117 function merge(){};
118 exports.merge = merge;
119 })(module, module.exports);
120 </code></pre>
121
122 <p>First create the file <em>./utils.js</em>, and define the <code>merge()</code> function as seen below. The implied anonymous wrapper function shown above allows us to seemingly define globals, however these are not accessible until exported.</p>
123
124 <pre><code> function merge(obj, other) {
125 var keys = Object.keys(other);
126 for (var i = 0, len = keys.length; i &lt; len; ++i) {
127 var key = keys[i];
128 obj[key] = other[key];
129 }
130 return obj;
131 };
132
133 exports.merge = merge;
134 </code></pre>
135
136 <p>The typical pattern for public properties is to simply define them
137 on the <code>exports</code> object like so:</p>
138
139 <pre><code>exports.merge = function(obj, other) {
140 var keys = Object.keys(other);
141 for (var i = 0, len = keys.length; i &lt; len; ++i) {
142 var key = keys[i];
143 obj[key] = other[key];
144 }
145 return obj;
146 };
147 </code></pre>
148
149 <p>Next we will look at utilizing out new module in other libraries.</p>
150
151 <h2 id="Requiring-Modules">Requiring Modules</h2>
152
153 <p>There are four main ways to require a module in node, first is the <em>synchronous</em> method, which simply returns the module's exports, second is the <em>asynchronous</em> method which accepts a callback, third is the <em>asynchronous http</em> method which can load remote modules, and lastly is requiring of shared libraries or "node addons" which we will cover later.</p>
154
155 <p>To get started create a second file named <em>./app.js</em> with the code shown below. The first line <code>require('./utils')</code> fetches the contents of <em>./utils.js</em> and returns the <code>exports</code> of which we later utilize our <code>merge()</code> method and display the results of our merged object using <code>console.dir()</code>.</p>
156
157 <pre><code>var utils = require('./utils');
158
159 var a = { one: 1 };
160 var b = { two: 2 };
161 utils.merge(a, b);
162 console.dir(a);
163 </code></pre>
164
165 <p>Core modules such as the <em>sys</em> which are bundled with node can be required without a path, such as <code>require('sys')</code>, however 3rd-party modules will iterate the <code>require.paths</code> array in search of a module matching the given path. By default <code>require.paths</code> includes <em>~/.node_libraries</em>, so if <em>~/.node_libraries</em>/utils.js_ exists we may simply <code>require('utils')</code>, instead of our relative example <code>require('./utils')</code> shown above.</p>
166
167 <p>Node also supports the concept of <em>index</em> JavaScript files. To illustrate this example lets create a <em>math</em> module that will provide the <code>math.add()</code>, and <code>math.sub()</code> methods. For organizational purposes we will keep each method in their respective <em>./math/add.js</em> and <em>./math/sub.js</em> files. So where does <em>index.js</em> come into play? we can populate <em>./math/index.js</em> with the code shown below, which is used when <code>require('./math')</code> is invoked, which is conceptually identical to invoking <code>require('./math/index')</code>.</p>
168
169 <pre><code>module.exports = {
170 add: require('./add'),
171 sub: require('./sub')
172 };
173 </code></pre>
174
175 <p>The contents of <em>./math/add.js</em> show us a new technique, here we use <code>module.exports</code> instead of <code>exports</code>. Previously mentioned was the fact that <code>exports</code> is not the only object exposed to the module file when evaluated, we also have access to <code>__dirname</code>, <code>__filename</code>, and <code>module</code> which represents the current module. Here we simply define the module export object to a new object, which happens to be a function.</p>
176
177 <pre><code>module.exports = function add(a, b){
178 return a + b;
179 };
180 </code></pre>
181
182 <p>This technique is usually only helpful when your module has one aspect that it wishes to expose, be it a single function, constructor, string, etc. Below is an example of how we could provide the <code>Animal</code> constructor:</p>
183
184 <pre><code>exports.Animal = function Animal(){};
185 </code></pre>
186
187 <p>which can then be utilized as shown:</p>
188
189 <pre><code>var Animal = require('./animal').Animal;
190 </code></pre>
191
192 <p>if we change our module slightly, we can remove <code>.Animal</code>:</p>
193
194 <pre><code>module.exports = function Animal(){};
195 </code></pre>
196
197 <p>which can now be used without the property:</p>
198
199 <pre><code>var Animal = require('./animal');
200 </code></pre>
201
202 <h2 id="Require-Paths">Require Paths</h2>
203
204 <p>We talked about <code>require.paths</code>, the <code>Array</code> utilized by node's module system in order to discover modules. By default node checks the following directories for modules:</p>
205
206 <ul>
207 <li><code>&lt;node binary></code>/../../lib/node</li>
208 <li><strong>$HOME</strong>/.node_libraries</li>
209 <li><strong>$NODE_PATH</strong></li>
210 </ul>
211
212
213 <p>The <strong>NODE_PATH</strong> environment variable is much like <strong>PATH</strong>, as it allows several paths delimited by the colon (<code>:</code>) character.</p>
214
215 <h3 id="Runtime-Manipulation">Runtime Manipulation</h3>
216
217 <p>Since <code>require.paths</code> is just an array, we can manipulate it at runtime in order to expose libraries. In our previous example we defined the libraries <em>./math/{add,sub}.js</em>, in which we would typically <code>require('./math')</code> or <code>require('./math/add')</code> etc. Another approach is to prepend or "unshift" a directory onto <code>require.paths</code> as shown below, after which we can simply <code>require('add')</code> since node will iterate the paths in order to try and locate the module.</p>
218
219 <pre><code>require.paths.unshift(__dirname + '/math');
220
221 var add = require('add'),
222 sub = require('sub');
223
224 console.log(add(1,2));
225 console.log(sub(1,2));
226 </code></pre>
227
228 <h2 id="Pseudo-Globals">Pseudo Globals</h2>
229
230 <p>As mentioned above, modules have several pseudo globals available to them, these are as follows:</p>
231
232 <ul>
233 <li><code>require</code> the require function itself</li>
234 <li><code>module</code> the current <code>Module</code> instance</li>
235 <li><code>exports</code> the current module's exported properties</li>
236 <li><code>__filename</code> absolute path to the current module's file</li>
237 <li><code>__dirname</code> absolute path to the current module's directory</li>
238 </ul>
239
240
241 <h3 id="require-">require()</h3>
242
243 <p>Although not obvious at first glance, the <code>require()</code> function is actually
244 re-defined for the current module, and calls an internal function <code>loadModule</code> with a reference to the current <code>Module</code> to resolve relative paths and to populate <code>module.parent</code>.</p>
245
246 <h3 id="module">module</h3>
247
248 <p>When we <code>require()</code> a module, typically we only deal with the module's <code>exports</code>, however the <code>module</code> variable references the current module's <code>Module</code> instance. This is why the following is valid, as we may re-assign the module's <code>exports</code> to any object, even something trivial like a string:</p>
249
250 <pre><code>// css.js
251 module.exports = 'body { background: blue; }';
252 </code></pre>
253
254 <p>To obtain this string we would simply <code>require('./css')</code>. The <code>module</code> object also contains these useful properties:</p>
255
256 <ul>
257 <li><code>id</code> the module's id, consisting of a path. Ex: <code>./app</code></li>
258 <li><code>parent</code> the parent <code>Module</code> (which required this one) or <code>undefined</code></li>
259 <li><code>filename</code> absolute path to the module</li>
260 <li><code>moduleCache</code> an object containing references to all cached modules</li>
261 </ul>
262
263
264 <h2 id="Asynchronous-Require">Asynchronous Require</h2>
265
266 <p>Node provides us with an asynchronous version of <code>require()</code>, aptly named <code>require.async()</code>. Below is the sample example previously shown for our <em>utils</em> module, however non blocking. <code>require.async()</code> accepts a callback of which the first parameter <code>err</code> is <code>null</code> or an instanceof <code>Error</code>, and then the module exports. Passing the error (if there is one) as the first argument is an extremely common idiom in node for async routines.</p>
267
268 <pre><code>require.async('./utils', function(err, utils){
269 console.dir(utils.merge({ foo: 'bar' }, { bar: 'baz' }));
270 });
271 </code></pre>
272
273 <h2 id="Requiring-Over-HTTP">Requiring Over HTTP</h2>
274
275 <p>Asynchronous requires in node also have the added bonus of allowing module loading via <strong>HTTP</strong> and <strong>HTTPS</strong>.
276 To require a module via http all we have to do is pass a valid url as shown in the <em>sass</em> to <em>css</em> compilation example below:</p>
277
278 <pre><code>var sassUrl = 'http://github.com/visionmedia/sass.js/raw/master/lib/sass.js',
279 sassStr = ''
280 + 'body\n'
281 + ' a\n'
282 + ' :color #eee';
283
284 require.async(sassUrl, function(err, sass){
285 var str = sass.render(sassStr);
286 console.log(str);
287 });
288 </code></pre>
289
290 <p>Outputs:</p>
291
292 <pre><code>body a {
293 color: #eee;}
294 </code></pre>
295
296 <h2 id="Registering-Module-Compilers">Registering Module Compilers</h2>
297
298 <p>Another cool feature that node provides us, is the ability to register compilers for a specific file extension. A good example of this is the CoffeeScript language, which is a ruby/python inspired language compiling to vanilla JavaScript, and through the use of <code>require.registerExtension()</code> can do so in an automated fashion.</p>
299
300 <p>To illustrate it's usage, lets create a small (and useless) Extended JavaScript language, or "ejs" for our example which will live at <em>./compiler/example.ejs</em>, it's syntax will look like this:</p>
301
302 <pre><code>::min(a, b) a &lt; b ? a : b
303 ::max(a, b) a &gt; b ? a : b
304 </code></pre>
305
306 <p>which will be compiled to:</p>
307
308 <pre><code>exports.min = function min(a, b) { return a &lt; b ? a : b }
309 exports.max = function max(a, b) { return a &gt; b ? a : b }
310 </code></pre>
311
312 <p>First lets create the module that will actually be doing the ejs to JavaScript compilation. In this example it is located at <em>./compiler/extended.js</em>, and exports a single method named <code>compile()</code>. This method accepts a string, which is the raw contents of what node is requiring, transformed to vanilla JavaScript via regular expressions.</p>
313
314 <pre><code>exports.compile = function(str){
315 return str
316 .replace(/(\w+)\(/g, '$1 = function $1(')
317 .replace(/\)(.+?)\n/g, '){ return $1 }\n')
318 .replace(/::/g, 'exports.');
319 };
320 </code></pre>
321
322 <p>Next we have to "register" the extension to assign out compiler. As previously mentioned our compiler lives at <em>./compiler/extended.js</em> so we are requiring it in, and passing the <code>compile()</code> method to <code>require.registerExtension()</code> which simply expects a function accepting a string, and returning a string of JavaScript.</p>
323
324 <pre><code>require.registerExtension('.ejs', require('./compiler/extended').compile);
325 </code></pre>
326
327 <p>Now when we require our example, the ".ejs" extension is detected, and will pass the contents through our compiler, and everything works as expected.</p>
328
329 <pre><code>var example = require('./compiler/example');
330 console.dir(example)
331 console.log(example.min(2, 3));
332 console.log(example.max(10, 8));
333
334 // =&gt; { min: [Function], max: [Function] }
335 // =&gt; 2
336 // =&gt; 10
337 </code></pre>
338
339 </div>
340 <div class='mp'>
341 <h1>Globals</h1>
342 <p> As we have learnt node's module system discourages the use of globals, however node provides a few important globals for use to utilize. The first and most important is the <code>process</code> global which exposes process manipulation such as signalling, exiting, the process id (pid), and more. Other globals help drive to be similar to other familiar JavaScript environments such as the browser, by providing a <code>console</code> object.</p>
343
344 <h2 id="console">console</h2>
345
346 <p>The <code>console</code> object contains several methods which are used to output information to <em>stdout</em> or <em>stderr</em>. Lets take a look at what each method does.</p>
347
348 <h3 id="console-log-">console.log()</h3>
349
350 <p>The most frequently used console method is <code>console.log()</code> simply writing to <em>stdout</em> with a line feed (<code>\n</code>). Currently aliased as <code>console.info()</code>.</p>
351
352 <pre><code>console.log('wahoo');
353 // =&gt; wahoo
354
355 console.log({ foo: 'bar' });
356 // =&gt; [object Object]
357 </code></pre>
358
359 <h3 id="console-error-">console.error()</h3>
360
361 <p>Identical to <code>console.log()</code>, however writes to <em>stderr</em>. Aliased as <code>console.warn()</code> as well.</p>
362
363 <pre><code>console.error('database connection failed');
364 </code></pre>
365
366 <h3 id="console-dir-">console.dir()</h3>
367
368 <p>Utilizes the <em>sys</em> module's <code>inspect()</code> method to pretty-print the object to
369 <em>stdout</em>.</p>
370
371 <pre><code>console.dir({ foo: 'bar' });
372 // =&gt; { foo: 'bar' }
373 </code></pre>
374
375 <h3 id="console-assert-">console.assert()</h3>
376
377 <p>Asserts that the given expression is truthy, or throws an exception.</p>
378
379 <pre><code>console.assert(connected, 'Database connection failed');
380 </code></pre>
381
382 <h2 id="process">process</h2>
383
384 <p>The <code>process</code> object is plastered with goodies, first we will take a look
385 at some properties that provide information about the node process itself.</p>
386
387 <h3 id="process-version">process.version</h3>
388
389 <p>The version property contains the node version string, for example "v0.1.103".</p>
390
391 <h3 id="process-installPrefix">process.installPrefix</h3>
392
393 <p>Exposes the installation prefix, in my case "<em>/usr/local</em>", as node's binary was installed to "<em>/usr/local/bin/node</em>".</p>
394
395 <h3 id="process-execPath">process.execPath</h3>
396
397 <p>Path to the executable itself "<em>/usr/local/bin/node</em>".</p>
398
399 <h3 id="process-platform">process.platform</h3>
400
401 <p>Exposes a string indicating the platform you are running on, for example "darwin".</p>
402
403 <h3 id="process-pid">process.pid</h3>
404
405 <p>The process id.</p>
406
407 <h3 id="process-cwd-">process.cwd()</h3>
408
409 <p>Returns the current working directory, for example:</p>
410
411 <pre><code>cd ~ &amp;&amp; node
412 node&gt; process.cwd()
413 "/Users/tj"
414 </code></pre>
415
416 <h3 id="process-chdir-">process.chdir()</h3>
417
418 <p>Changes the current working directory to the path passed.</p>
419
420 <pre><code>process.chdir('/foo');
421 </code></pre>
422
423 <h3 id="process-getuid-">process.getuid()</h3>
424
425 <p>Returns the numerical user id of the running process.</p>
426
427 <h3 id="process-setuid-">process.setuid()</h3>
428
429 <p>Sets the effective user id for the running process. This method accepts both a numerical id, as well as a string. For example both <code>process.setuid(501)</code>, and <code>process.setuid('tj')</code> are valid.</p>
430
431 <h3 id="process-getgid-">process.getgid()</h3>
432
433 <p>Returns the numerical group id of the running process.</p>
434
435 <h3 id="process-setgid-">process.setgid()</h3>
436
437 <p>Similar to <code>process.setuid()</code> however operates on the group, also accepting a numerical value or string representation. For example <code>process.setgid(20)</code> or <code>process.setgid('www')</code>.</p>
438
439 <h3 id="process-env">process.env</h3>
440
441 <p>An object containing the user's environment variables, for example:</p>
442
443 <pre><code>{ PATH: '/Users/tj/.gem/ruby/1.8/bin:/Users/tj/.nvm/current/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin'
444 , PWD: '/Users/tj/ebooks/masteringnode'
445 , EDITOR: 'mate'
446 , LANG: 'en_CA.UTF-8'
447 , SHLVL: '1'
448 , HOME: '/Users/tj'
449 , LOGNAME: 'tj'
450 , DISPLAY: '/tmp/launch-YCkT03/org.x:0'
451 , _: '/usr/local/bin/node'
452 , OLDPWD: '/Users/tj'
453 }
454 </code></pre>
455
456 <h3 id="process-argv">process.argv</h3>
457
458 <p>When executing a file with the <code>node</code> executable <code>process.argv</code> provides access to the argument vector, the first value being the node executable, second being the filename, and remaining values being the arguments passed.</p>
459
460 <p>For example our source file <em>./src/process/misc.js</em> can be executed by running:</p>
461
462 <pre><code>$ node src/process/misc.js foo bar baz
463 </code></pre>
464
465 <p>in which we call <code>console.dir(process.argv)</code>, outputting the following:</p>
466
467 <pre><code>[ 'node'
468 , '/Users/tj/EBooks/masteringnode/src/process/misc.js'
469 , 'foo'
470 , 'bar'
471 , 'baz'
472 ]
473 </code></pre>
474
475 <h3 id="process-exit-">process.exit()</h3>
476
477 <p>The <code>process.exit()</code> method is synonymous with the C function <code>exit()</code>, in which a exit code > 0 is passed indicating failure, or 0 to indicate success. When invoked the <em>exit</em> event is emitted, allowing a short time for arbitrary processing to occur before <code>process.reallyExit()</code> is called with the given status code.</p>
478
479 <h3 id="process-on-">process.on()</h3>
480
481 <p>The process itself is an <code>EventEmitter</code>, allowing you to do things like listen for uncaught exceptions, via the <em>uncaughtException</em> event:</p>
482
483 <pre><code>process.on('uncaughtException', function(err){
484 console.log('got an error: %s', err.message);
485 process.exit(1);
486 });
487
488 setTimeout(function(){
489 throw new Error('fail');
490 }, 100);
491 </code></pre>
492
493 <h3 id="process-kill-">process.kill()</h3>
494
495 <p><code>process.kill()</code> method sends the signal passed to the given <em>pid</em>, defaulting to <strong>SIGINT</strong>. In our example below we send the <strong>SIGTERM</strong> signal to the same node process to illustrate signal trapping, after which we output "terminating" and exit. Note that our second timeout of 1000 milliseconds is never reached.</p>
496
497 <pre><code>process.on('SIGTERM', function(){
498 console.log('terminating');
499 process.exit(1);
500 });
501
502 setTimeout(function(){
503 console.log('sending SIGTERM to process %d', process.pid);
504 process.kill(process.pid, 'SIGTERM');
505 }, 500);
506
507 setTimeout(function(){
508 console.log('never called');
509 }, 1000);
510 </code></pre>
511
512 <h3 id="errno">errno</h3>
513
514 <p>The <code>process</code> object is host of the error numbers, these reference what you would find in C-land, for example <code>process.EPERM</code> represents a permission based error, while <code>process.ENOENT</code> represents a missing file or directory. Typically these are used within bindings to bridge the gap between c++ and JavaScript, however useful for handling exceptions as well:</p>
515
516 <pre><code>if (err.errno === process.ENOENT) {
517 // Display a 404 "Not Found" page
518 } else {
519 // Display a 500 "Internal Server Error" page
520 }
521 </code></pre>
522
523 </div>
524 <div class='mp'>
525 <h1>Events</h1>
2f6a03c @tj Added mobi and epub to `make all`
tj authored
526 <p> The concept of an "event" is crucial to node, and used greatly throughout core and 3rd-party modules. Node's core module <em>events</em> supplies us with a single constructor, <em>EventEmitter</em>.</p>
2a420a7 @tj No longer gitignoring html
tj authored
527
528 <h2 id="Emitting-Events">Emitting Events</h2>
529
530 <p>Typically an object inherits from <em>EventEmitter</em>, however our small example below illustrates the api. First we create an <code>emitter</code>, after which we can define any number of callbacks using the <code>emitter.on()</code> method which accepts the <em>name</em> of the event, and arbitrary objects passed as data. When <code>emitter.emit()</code> is called we are only required to pass the event <em>name</em>, followed by any number of arguments, in this case the <code>first</code> and <code>last</code> name strings.</p>
531
532 <pre><code>var EventEmitter = require('events').EventEmitter;
533
534 var emitter = new EventEmitter;
535
536 emitter.on('name', function(first, last){
537 console.log(first + ', ' + last);
538 });
539
540 emitter.emit('name', 'tj', 'holowaychuk');
541 emitter.emit('name', 'simon', 'holowaychuk');
542 </code></pre>
543
544 <h2 id="Inheriting-From-EventEmitter">Inheriting From EventEmitter</h2>
545
546 <p>A perhaps more practical use of <code>EventEmitter</code>, and commonly used throughout node is to inherit from it. This means we can leave <code>EventEmitter</code>'s prototype untouched, while utilizing it's api for our own means of world domination!</p>
547
548 <p>To do so we begin by defining the <code>Dog</code> constructor, which of course will bark from time to time, also known as an <em>event</em>. Our <code>Dog</code> constructor accepts a <code>name</code>, followed by <code>EventEmitter.call(this)</code>, which invokes the <code>EventEmitter</code> function in context to the given argument. Doing this is essentially the same as a "super" or "parent" call in languages that support classes. This is a crucial step, as it allows <code>EventEmitter</code> to set up the <code>_events</code> property which it utilizes internally to manage callbacks.</p>
549
550 <pre><code>var EventEmitter = require('events').EventEmitter;
551
552 function Dog(name) {
553 this.name = name;
554 EventEmitter.call(this);
555 }
556 </code></pre>
557
558 <p>Here we inherit from <code>EventEmitter</code>, so that we may use the methods provided such as <code>EventEmitter#on()</code> and <code>EventEmitter#emit()</code>. If the <code>__proto__</code> property is throwing you off, no worries! we will be touching on this later.</p>
559
560 <pre><code>Dog.prototype.__proto__ = EventEmitter.prototype;
561 </code></pre>
562
563 <p>Now that we have our <code>Dog</code> set up, we can create .... simon! When simon barks we can let <em>stdout</em> know by calling <code>console.log()</code> within the callback. The callback it-self is called in context to the object, aka <code>this</code>.</p>
564
565 <pre><code>var simon = new Dog('simon');
566
567 simon.on('bark', function(){
568 console.log(this.name + ' barked');
569 });
570 </code></pre>
571
572 <p>Bark twice a second:</p>
573
574 <pre><code>setInterval(function(){
575 simon.emit('bark');
576 }, 500);
577 </code></pre>
578
579 <h2 id="Removing-Event-Listeners">Removing Event Listeners</h2>
580
581 <p>As we have seen event listeners are simply functions which are called when we <code>emit()</code> an event. Although not seen often we can remove these listeners by calling the <code>removeListener(type, callback)</code> method. In the example below we emit the <em>message</em> "foo bar" every <code>300</code> milliseconds, which has the callback of <code>console.log()</code>. After 1000 milliseconds we call <code>removeListener()</code> with the same arguments that we passed to <code>on()</code> originally. To compliment this method is <code>removeAllListeners(type)</code> which removes all listeners associated to the given <em>type</em>.</p>
582
583 <pre><code>var EventEmitter = require('events').EventEmitter;
584
585 var emitter = new EventEmitter;
586
587 emitter.on('message', console.log);
588
589 setInterval(function(){
590 emitter.emit('message', 'foo bar');
591 }, 300);
592
593 setTimeout(function(){
594 emitter.removeListener('message', console.log);
595 }, 1000);
596 </code></pre>
597
598 </div>
599 <div class='mp'>
600 <h1>Buffers</h1>
2f6a03c @tj Added mobi and epub to `make all`
tj authored
601 <p> To handle binary data, node provides us with the global <code>Buffer</code> object. Buffer instances represent memory allocated independently to that of V8's heap. There are several ways to construct a <code>Buffer</code> instance, and many ways you can manipulate it's data.</p>
2a420a7 @tj No longer gitignoring html
tj authored
602
603 <p>The simplest way to construct a <code>Buffer</code> from a string is to simply pass a string as the first argument. As you can see by the log output, we now have a buffer object containing 5 bytes of data represented in hexadecimal.</p>
604
605 <pre><code>var hello = new Buffer('Hello');
606
607 console.log(hello);
608 // =&gt; &lt;Buffer 48 65 6c 6c 6f>
609
610 console.log(hello.toString());
611 // =&gt; "Hello"
612 </code></pre>
613
614 <p>By default the encoding is "utf8", however this can be specified by passing as string as the second argument. The ellipsis below for example will be printed to stdout as the '&amp;' character when in "ascii" encoding.</p>
615
616 <pre><code>var buf = new Buffer('…');
617 console.log(buf.toString());
618 // =&gt;
619
620 var buf = new Buffer('…', 'ascii');
621 console.log(buf.toString());
622 // =&gt; &amp;
623 </code></pre>
624
625 <p>An alternative method is to pass an array of integers representing the octet stream, however in this case functionality equivalent.</p>
626
627 <pre><code>var hello = new Buffer([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
628 </code></pre>
629
630 <p>Buffers can also be created with an integer representing the number of bytes allocated, after which we may call the <code>write()</code> method, providing an optional offset and encoding. As shown below we provide the offset of 2 bytes to our second call to <code>write()</code>, buffering "Hel", and then we continue on to write another two bytes with an offset of 3, completing "Hello".</p>
631
632 <pre><code>var buf = new Buffer(5);
633 buf.write('He');
634 buf.write('l', 2);
635 buf.write('lo', 3);
636 console.log(buf.toString());
637 // =&gt; "Hello"
638 </code></pre>
639
2f6a03c @tj Added mobi and epub to `make all`
tj authored
640 <p>The <code>.length</code> property of a buffer instance contains the byte length of the stream, opposed to JavaScript strings which will simply return the number of characters. For example the ellipsis character '…' consists of three bytes, however the buffer will respond with the byte length, and not the character length.</p>
2a420a7 @tj No longer gitignoring html
tj authored
641
642 <pre><code>var ellipsis = new Buffer('…', 'utf8');
643
644 console.log('… string length: %d', '…'.length);
645 // =&gt; … string length: 1
646
647 console.log('… byte length: %d', ellipsis.length);
648 // =&gt; … byte length: 3
649
650 console.log(ellipsis);
651 // =&gt; &lt;Buffer e2 80 a6>
652 </code></pre>
653
2f6a03c @tj Added mobi and epub to `make all`
tj authored
654 <p>When dealing with JavaScript strings, we may pass it to the <code>Buffer.byteLength()</code> method to determine it's byte length.</p>
2a420a7 @tj No longer gitignoring html
tj authored
655
2f6a03c @tj Added mobi and epub to `make all`
tj authored
656 <p>The api is written in such a way that it is String-like, so for example we can work with "slices" of a <code>Buffer</code> by passing offsets to the <code>slice()</code> method:</p>
2a420a7 @tj No longer gitignoring html
tj authored
657
658 <pre><code>var chunk = buf.slice(4, 9);
659 console.log(chunk.toString());
660 // =&gt; "some"
661 </code></pre>
662
663 <p>Alternatively when expecting a string we can pass offsets to <code>Buffer#toString()</code>:</p>
664
665 <pre><code>var buf = new Buffer('just some data');
666 console.log(buf.toString('ascii', 4, 9));
667 // =&gt; "some"
668 </code></pre>
669
670 </div>
671 <div class='mp'>
672 <h1>Streams</h1>
673 <p> Streams are an important concept in node. The stream api is a unified way to handle stream-like data, for example data can be streamed to a file, streamed to a socket to respond to an HTTP request, or a stream can be read-only such as reading from <em>stdin</em>. However since we will be touching on stream specifics in later chapters, for now we will concentrate on the api.</p>
674
675 <h2 id="Readable-Streams">Readable Streams</h2>
676
677 <p> Readable streams such as an HTTP request inherit from <code>EventEmitter</code> in order to expose incoming data through events. The first of these events is the <em>data</em> event, which is an arbitrary chunk of data passed to the event handler as a <code>Buffer</code> instance.</p>
678
679 <pre><code>req.on('data', function(buf){
680 // Do something with the Buffer
681 });
682 </code></pre>
683
684 <p>As we know, we can call <code>toString()</code> a buffer to return a string representation of the binary data, however in the case of streams if desired we may call <code>setEncoding()</code> on the stream,
685 after which the <em>data</em> event will emit strings.</p>
686
687 <pre><code>req.setEncoding('utf8');
688 req.on('data', function(str){
689 // Do something with the String
690 });
691 </code></pre>
692
693 <p>Another import event is the <em>end</em> event, which represents the ending of <em>data</em> events. For example below we define an HTTP echo server, simply "pumping" the request body data through to the response. So if we <strong>POST</strong> "hello world", our response will be "hello world".</p>
694
695 <pre><code>var http = require('http');
696
697 http.createServer(function(req, res){
698 res.writeHead(200);
699 req.on('data', function(data){
700 res.write(data);
701 });
702 req.on('end', function(){
703 res.end();
704 });
705 }).listen(3000);
706 </code></pre>
707
708 <p>The <em>sys</em> module actually has a function designed specifically for this "pumping" action, aptly named <code>sys.pump()</code>, which accepts a read stream as the first argument, and write stream as the second.</p>
709
710 <pre><code>var http = require('http'),
711 sys = require('sys');
712
713 http.createServer(function(req, res){
714 res.writeHead(200);
715 sys.pump(req, res);
716 }).listen(3000);
717 </code></pre>
718
719 </div>
720 <div class='mp'>
721 <h1>File System</h1>
722 <p> ...</p>
723
724 </div>
725 <div class='mp'>
726 <h1>TCP</h1>
727 <p> ...</p>
728
729 <h2 id="TCP-Servers">TCP Servers</h2>
730
731 <p> ...</p>
732
733 <h2 id="TCP-Clients">TCP Clients</h2>
734
735 <p> ...</p>
736
737 </div>
738 <div class='mp'>
739 <h1>HTTP</h1>
740 <p> ...</p>
741
742 <h2 id="HTTP-Servers">HTTP Servers</h2>
743
744 <p> ...</p>
745
746 <h2 id="HTTP-Clients">HTTP Clients</h2>
747
748 <p> ...</p>
749
750 </div>
751 <div class='mp'>
752 <h1>Connect</h1>
753 <p>Connect is a ...</p>
754
755 </div>
756 <div class='mp'>
757 <h1>Express</h1>
758 <p>Express is a ...</p>
759
760 </div>
761 <div class='mp'>
762 <h1>Testing</h1>
763 <p> ...</p>
764
765 <h2 id="Expresso">Expresso</h2>
766
767 <p> ...</p>
768
769 <h2 id="Vows">Vows</h2>
770
771 <p> ...</p>
772
773 </div>
774 <div class='mp'>
775 <h1>Deployment</h1>
776 <p> ...</p>
777
778 </div>
779 </body>
780 </html>
Something went wrong with that request. Please try again.