Slashdot Mirror


Book Review: Sams Teach Yourself Node.js In 24 Hours

Michael Ross writes "Since its introduction in 1994, JavaScript has largely been utilized within web browsers, which limited JavaScript programmers to client-side development. Yet with the recent introduction of Node.js, those programmers can leverage their skills and experience for server-side efforts. Node.js is an event-based framework for creating network applications — particularly those for the Web. Anyone interested in learning this relatively new technology can begin with one of numerous resources, including Sams Teach Yourself Node.js in 24 Hours." Keep reading for the rest of Michael's review. Sams Teach Yourself Node.js in 24 Hours author George Ornbo pages 464 pages publisher Sams Publishing rating 7/10 reviewer Michael J. Ross ISBN 978-0672335952 summary An introduction to the Node.js framework. This book, authored by George Ornbo, was released by Sams Publishing on 15 September 2012, under the ISBN 978-0672335952. The recent publication date is promising, because Node.js is evolving rapidly, thus gradually obsoleting books written not that long ago. On the publisher's page, visitors will find a brief description of Ornbo's book, a few customer reviews, the table of contents, a sample chapter (the 14th, "A Streaming Twitter Client"), and links to purchase the print and electronic versions of the book. There is also a link to the companion site, which offers some of the same content as Pearson's page, but also has a link to download an archive file containing all the example code, nicely organized.

The book's material spans 464 pages, and is organized (shoehorned) into 24 "hours" (chapters), grouped into six parts. The first two chapters in "Getting Started" explain how the reader can download Node.js, create a "hello world" web server program, install new modules using npm (Node Packaged Modules), search for modules, locate documentation on them, and indicate module dependencies for an application. Unfortunately, the blocks of source code presented in the first examples (Listing 1.1 and Figure 2.2) are not explained in the narrative (until the fifth chapter) or even commented. Readers would likely appreciate some clues as to the nature of http.createServer, req, res, the "underscore" module, etc. — especially at the beginning of their journey. If readers are not expected to understand these details at this point, then they should be told so, to avoid any concerns that such an understanding is assumed in the subsequent chapters. The author does not explain where Node.js is installed or what changes it makes to the terminal's default path variable. On page 18, the term "project folder" is unclear: should the "underscore" module end up in hour02/example01/node_modules, or nodejs/node_modules, or nodejs/node_modules/npm/node_modules? Only later is this (partially) answered.

Chapter 3 demonstrates the complexity that arises from concurrent input/output in networked applications. This material should arguably have been presented at the beginning of the book, to better establish the purpose of Node.js, and the value to the reader of studying it. The next chapter summarizes jQuery and JavaScript callbacks, and then provides a helpful discussion of how Node.js uses the latter. The author contends that the asynchronous paradigm of Node.js is unsuitable for long-running processes, but does not explain why this is true, which would have provided some substantiation for the claim.

The second part of the book, "Basic Websites With Node.js," encompasses four more chapters. The first one discusses how to: create a simple server (using the core HTTP module), examine the response headers (generated for web pages, in different browsers and on the Linux command line), execute 301 redirects, respond to different types of requests (using the URL module), and create a simple client. Oddly, the author does not explain or even mention the sizable JSON output — the first line of which is "{ domain: null," — displayed in the reader's server terminal when the web page pointing to that server is refreshed or when the "curl -I" command is run. The next two chapters cover how to build websites using the Express framework, and are likely the first point where the reader will see some of the real-world complexity of Node.js. The eighth chapter explains how to persist data between calls to the application, including files, environment variables, and MongoDB.

Debugging, testing, and deploying are all critical topics for any application development, and are covered in the third part of the book. The author illustrates three methods of debugging: STDIO, a core module, is a lightweight method for debugging Node.js code; it allows one to output messages to the console, check the value of any variable or literal, and track function calls and responses from third-party services. Node.js provides access to the more powerful debugger of V8 (the Google Chrome JavaScript engine), which supports breakpoints and code stepping. Node Inspector, compatible with WebKit-based browsers, provides all of the above functionality, and more. The next two chapters present several modules that ease the important process of creating full-coverage tests, and demonstrate how to deploy applications to any one of three Node.js-capable cloud hosting providers (Heroku, Cloud Foundry, and Nodester).

Having covered the basics of Node.js, the author begins the fourth part of his book with two chapters that show how to use Socket.IO, WebSockets, and Express to build real-time web applications. These techniques are illustrated in the development of a chat server as well as a nickname management and messaging system. The aforementioned sample chapter extends these techniques further in working with the Twitter API to consume its real-time data, push it to the browser, and show results in a dynamic graph. This section is wrapped up with coverage primarily of JSON — specifically, how to create, consume, and send JSON-structured data.

APIs were addressed briefly in the previous section, but are explored much more deeply in the subsequent five chapters. Readers may initially conclude that the discussion of processes is elementary, but the author then shows how one could utilize that knowledge to interact with Node.js scripts, including detecting script exits and errors, sending signals and arguments to a script, generating child processes if needed, and sending messages among them. In the 18th chapter, the author goes into greater detail about Node.js's Events module, best practices, and how to generate event listeners dynamically. The buffer API may be low-level, but it is essential for storing raw binary data, as opposed to the Unicode-encoded strings that JavaScript uses within a browser. The Buffer and Stream modules are presented with plenty of helpful examples.

The last part of the book addresses miscellaneous topics, starting with CoffeeScript (a JavaScript precompiler). While CoffeeScript affords numerous benefits, it is not clear why it would deserve an entire chapter in a book dedicated to Node.js. In the next chapter, readers learn how to verify their Node.js code, add command-line executables, and then package it all up into portable modules that can be contributed to the npm registry or GitHub. The last two chapters explain how to create and configure middleware using the Connect module, and how to use Backbone.js (a front-end JavaScript framework) in conjunction with Node.js to build browser-based web applications.

Each chapter concludes with a summary (invariably a waste of space), a Q&A section, a workshop comprising quiz questions (with the answers presented immediately below it, for almost instant spoiling), and several exercises for the reader.The index at the end is missing several of the important topics discussed in the text.

The book contains many errata: "EBay" (page 1; should read "eBay"), "OSX" (page 9; presumably Mac OS X), "yaml" (page 15; should read "YAML"), "irc" (19), "led to [a] great deal" (27), "to solve Concurrency" (37), "process" (54; should read "processes"), "try and" (55; should read "try to"), "This goal" (56; should read "The goal"), "how [a] class" (56), "You will [see] the" (62), "status of [a] web server" (70), "javascripts" (77), and "then [the] name" (87). At this point, less than 20 percent into the book, it was clear that the copyeditors had done a sloppy job, so I stopped recording these flaws that should have been caught. Those first four errata suggest that "textese" is even pervading the world of technical publishing. (Strangely, there does not appear to be a place on the publisher's website for reporting errata.)

The production team should have been looking for places to cut down on the heft of the print edition. The "Try It Yourself " sections sometimes duplicate what is found in the regular text nearby — especially in the third and fourth chapters. For instance, three sets of HTML markup are repeated, as well as the surrounding discussion (pages 42 through 47).

In general, the text does not appear to have been carefully scrutinized by technical reviewers and copyeditors. Occasionally the reader is given critical information later than would be optimal, e.g., the "Watch Out" warning on page 18, provided after the reader installs a module. The writing style is noticeably awkward in countless places in the book, including several run-on sentences. (Technical authors should not be bashful in using commas when doing so would help readability.) Also, the text is littered with too many exclamation marks — as if that is going to make any narrative more exciting.

In terms of the production quality of the book, a lay-flat binding would have made it much easier to read when using both hands on the keyboard. Also, in my review copy (kindly provided by the publisher), a disappointingly large number of the pages had small black splotches of ink; fortunately, none made the text unreadable.

On the other hand, Node.js is certainly not a simple subject area, and this book is able to convey a lot of information about it. This book's forte is the extensive use of example code to illustrate the concepts being presented. Incidentally, kudos to the author for inviting the reader to contribute to the Node.js community, such as adding new modules to GitHub or updating the documentation of existing modules. Overall, readers new to Node.js would certainly benefit from working their way through this volume.

Michael J. Ross is a freelance web developer and writer.

You can purchase Sams Teach Yourself Node.js in 24 Hours from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

29 of 112 comments (clear)

  1. Yup by gazbo · · Score: 3, Funny

    Before node.js it was literally impossible to use JS on a server. Thanks Node!!!1

    1. Re:Yup by Samantha+Wright · · Score: 5, Funny

      Pfft. So archaic. You should see the new JS frameworks. They're a blast.

      --
      Bio questions? Ask me to start a Q&A journal. Computer analogies available for most topics!
    2. Re:Yup by TwezerFace · · Score: 2

      literally impossible...how is that different from plain ole impossible?

  2. Re:Benefits by Spy+Handler · · Score: 4, Funny

    you can add cool sliding divs and blinking banners to your server console UI.

  3. Time for the Fad Dance, kiddies! by Anonymous Coward · · Score: 2, Insightful

    Yet ANOTHER JavaScript fad that we have to learn in 21 days or be outsourced to Timbuktu. My mother warned me to become a dentist.

    1. Re:Time for the Fad Dance, kiddies! by SJHillman · · Score: 4, Funny

      News For Molars, Floss That Matters

  4. Wrong question to ask by betterunixthanunix · · Score: 2

    The question is not, "what makes this better than languages that people typically use to write programs that run on servers?" but rather, "What is the benefit of Javascript as a language, and how can it make writing/maintaining applications easier?" or perhaps, "How can using Javascript make me more productive?"

    --
    Palm trees and 8
    1. Re:Wrong question to ask by Anonymous Coward · · Score: 3, Insightful

      What makes this better than languages that people typically use to write programs that run on servers?

      Nothing.

      What is the benefit of Javascript as a language, and how can it make writing/maintaining applications easier?

      No benefits, no ease.

      How can using Javascript make me more productive?

      Unless your productivity is a function of rage, it cannot.

    2. Re:Wrong question to ask by Unnngh! · · Score: 4, Insightful

      Lexical scoping, fast interpreted language, automatic memory management, same language client and server-side, dynamic typing, are all good reasons to use it, if you actually want all these things; otherwise there are almost certainly better choices. JavaScript is a really nice language if you ignore the parts of it that are terrible. The language is largely mis-understood and has a long history of abuse at the hands of those who mis-understand it. This is a real problem if you want to build a maintainable system and all the developers don't have a clear view of how to program well in JavaScript. The language is more like Lisp (specifically Scheme) than it is like Java, but not that many people know or even understand the idea behind Lisp nowadays. I would think that the resurgent interest in functional programming would ameliorate this to some extent but most of the JS I've worked on is crap and I would strongly recommend against using it unless you have a clear picture of why you would want to do so.

  5. Re:Benefits by i+kan+reed · · Score: 3, Insightful

    Your boss can say "Oh you're not a server developer? You are now! Experienced engineer who's familiar with backends, you're fired!"

  6. Re:or.. by multicoregeneral · · Score: 2

    Or how about, how to make your http requests stand in line for a half hour while they're parsed individually?

    --
    This signature intentionally left blank.
  7. Re:Benefits by multicoregeneral · · Score: 2

    Yeah, but you're suicidal if you put it on anything with traffic.

    --
    This signature intentionally left blank.
  8. Re:Benefits by multicoregeneral · · Score: 2

    Dude, if Javascript is your only skill, you're in serious trouble.

    --
    This signature intentionally left blank.
  9. Re:Does book include configuring host os? by Synerg1y · · Score: 2

    so basically... unfit for production environments is what you're getting at...

    Haven't done a whole lot of work with python, but I'd expect it to be fairly bug free at this point given how long it's been around and what it's used for typically.

  10. Re:TL;DR by Fallingcow · · Score: 2

    Are you talking about the book, or NodeJS itself?

  11. Great by Horshu · · Score: 2

    Just what the world needs - tinkering-level programmers utilizing their weakly-typed language skills in enterprise code.

  12. Re:Benefits by jellomizer · · Score: 2

    Primarily the benefit is that a Full Web Application can be done with one language.
    For some people switching between languages gets in the way, of writing uniformed code.
    Also I would expect that it would allow for easier movement from the prototype running in the browser and moved to the server.

    Or if you want to be more computer science purist. You can reuse functions and classes on your browser and on the server side. Often in web development you have to write code twice that does the same thing, because the browser will do an initial check, and the server will do the final (more secure) check. That and you will be using similar data structures.

    --
    If something is so important that you feel the need to post it on the internet... It probably isn't that important.
  13. I havent taken that long to learn a new language by peter303 · · Score: 3, Insightful

    I learned dozens over the decades. I can start coding in hours after looking at manual.
    To do it well is another issue.

  14. Dear God, why? by JDG1980 · · Score: 2, Informative

    JavaScript is a horrid language. Nonetheless, it's the only widely supported language for client-side browser code, so we're stuck with it there.

    But why on Earth would anyone even consider running this abomination on a server, when there are many other, better languages designed specifically for server-side code?

    1. Re:Dear God, why? by caknuckle · · Score: 5, Informative

      Some decent explanations here.

  15. Re:Benefits by Kergan · · Score: 4, Interesting

    What are the benefits of using javascript on the server side over a more typical server side programming language?

    You get to write every possible thing you need to use for your app, including basic things that aren't functional in the handful existing (albeit very dysfunctional) libraries.

    *Ducks*

    In all seriousness, there's a sweet spot when you're writing some app that needs a real-time, state-full, non-blocking environment, such as a chat server. There are of course alternatives, but this is what node.js was designed for.

    It does a good job at it, too, as long as you don't mind the tons of callbacks (read: impossible to follow spaghetti code), and the lack of decent debugging tools (unless this changed since last year?), the scarce (and occasionally unmaintained, and frequently buggy) libraries related to much about anything useful.

    My (admittedly scathing) take on node.js is this: it was created by a someone with a specific need, lots of love of javascript, and time to spend on reinventing the wheel instead of using more mature tools for the job. Many credits to him for being such an enthusiastic hobbyist who then open sourced his work. The issue is, it then got picked up by an army of web designers, as opposed to actual programmers. They thought "Oh great I can now code server stuff too!" and went off to write a library or three. And it shows, because nearly all of the libraries in question are borderline unusable except in very specific cases.

    In practice, node.js is a horror story littered with writing your own libraries for much about everything because testing existing ones revealed that they suffered from either or all of a missing feature, too many bugs, no maintainer, etc. As a hobbyist and potential library contributor, go there; you're much needed, and you'll even have fun if javascript turns you on. For actual development, just don't -- not even with a 10-foot pole.

  16. Re:Benefits by Kergan · · Score: 2

    Dude, if Javascript is your only skill, you're in serious trouble.

    The trouble is, this actually describes many a web developer's skill set happens to be. And it's a self-taught skill set at that.

  17. Re:Benefits by VoidEngineer · · Score: 4, Interesting

    It's actually a really huge advantage, if done correctly. A trivial example: I'm working on an app that has a file import functionality, so I wrote a half dozen helper functions to parse a spreadsheet into JSON. Later wound up using those same functions on the server to implement an XML interface. Business logic is the same in both instances, and having a single language for both server and client allows that business logic to be stored in a single place, maintaining the Don't Repeat Yourself (DRY) rule of thumb. Having a single language on both server and client is a godsend for keeping your app DRY.

  18. 464 pages by JustinKSU · · Score: 3, Insightful

    The title must be a joke. I can't even read 464 pages in 24 hours let alone be able to run the exercises necessary to actually learn it.

  19. Non-blocking is the secret in the async sauce by gnomff · · Score: 4, Funny
  20. Re:Does book include configuring host os? by corychristison · · Score: 2

    Just a quick note, as someone who has been fiddling with Node.js, they specifically say not to use Nginx or Apache as a front end proxy.

    Varnish seems to be the "just works" go to for Node.js proxies.

  21. Re:Benefits by arkhan_jg · · Score: 3, Funny

    It's faster than liquid manure off a buttered shovel.

    More seriously, node.js - as it's javascript - is ideal for asynchronous, non-blocking apps. When you think about a website, you need to be able to handle request n+1 promptly while you're still working on request n. i.e. while you're waiting for that database query to come back with the data you need to handle request n, you can still handle that entirely different new request without waiting for the first to finish.

    The whole design of node.js is to do that, and do it well.

    Node isn't the only server platform that works this way - python twisted springs to mind - but node has a built in event loop library that everything uses, whether it's your own code or plugin in modules. It makes it utterly trivial to add event listeners to 3rd party module events in your own code, and mix them in with your own event emitters for your own logic seemlessly. This is also handy when doing behaviour driven development with mocha (for example) - you can just add hooks to events in the code you're running the test suite to check it's working, and mock out inputs and even modules.

    The other option is callbacks, which are also universally supported. Call a function from a module (or your own), and pass a callback argument along with it - when the called function completes, it passes back the error and results to the callback. Big whoop. The key thing is that callbacks are non-blocking - so your server will happily be getting on with other things in the meantime. One mistake it's easy to make though is nested callbacks; if you want to do function A, B and C in order, it's easy to fall into the trap of putting B as an anonymous function in the callback of A, and C as an anonymous function in the callback of B - which rapidly leads to a horridly complex bit of nested code. You can either use a helper module like async, which gives you various options for running functions serially without writing a horrid mess; or use your own event emitters to announce when they're done, and have a listener wait for that to trigger the next step.

    One of the strengths of node is that you can easily build up your own server from modules. Ruby on Rails is fine if you want everything under one roof, and done the One True Way, but if you want to mix-n-match your own modules - web server, middleware, nosql or key-value store, imap, smtp, etc etc to fit in with your own code, then node is the way to go. This does mean you might need to do a bit more work putting the framework together, but you can use something like Express and its various addons to do most of the boilerplate for you with regards routing logic, static resources and middleware if you're doing a classic web app. JSON and binary buffers are built in to node, so you can easily handle AJAX responses and file streaming with minimum effort.

    In fact, everything is a module, and it's trivial to add in your own modules - and variables are local to that module, so you only end up with globals if you specifically ask for them, so avoiding polluting the namespace no matter how many modules you use.

    The last really huge strength of node.js is socket.io. Going from the one-way client-to-server ajax model, with a kinda kludgy server-to-client channel (xml long polling) to a true two-way server-client model so your server can directly send information to your client-side code without waiting to be asked for it is really, really powerful for truly responsive web apps - and will fall back to long-polling if using an older client that doesn't support it, so you don't have to hack about. It's arguably the most powerful feature of node - makes real-time apps an absolute walk in the park.

    OK, yes, it's javascript. Scoff away. Personally, I don't find it a problem, and being able to write client-side and server-side code in the same language is a plus - though to be honest, you tend to use quite different styles in node.js; client side is based heavily upon your framework (jquery, backbone, knockout, etc) more than 'va

    --
    Remember kids, it's all fun and games until someone commits wholesale galactic genocide.
  22. Re:Benefits by arkhan_jg · · Score: 2

    does a good job at it, too, as long as you don't mind the tons of callbacks (read: impossible to follow spaghetti code), and the lack of decent debugging tools (unless this changed since last year?), the scarce (and occasionally unmaintained, and frequently buggy) libraries related to much about anything useful.

    If you're writing a bunch of nested anonymous callbacks, you're doing it wrong - as you say, it looks ugly as sin and is a bugger to debug. Plus it means you may well be trying to wedge a synchronous workflow onto an asynchronous model. Either use something like async to get your control flow looking much cleaner if you absolutely must do things in specific order, or use events to announce when a section is done, so a pre-set listener can kick off the next section. Javascript is a very event driven language,and embracing as such drastically simplifies code.

    I'm not going to deny there are a bunch of unmaintained buggy modules out there, especially as node is evolving so quickly. But then, the same could be said about pretty much any frame work or open-source platform. As long as you stick to the 'mainstream', big modules, they're solid and do the job, and there's plenty of those now - it's a lot more robust environment than it was a year or two ago, and it will no doubt continue to mature.

    --
    Remember kids, it's all fun and games until someone commits wholesale galactic genocide.
  23. Re:I havent taken that long to learn a new languag by LordLucless · · Score: 2

    Good for you. Sadly, node.js isn't a language - it's a framework. And most languages have been through a *lot* more testing before they're shoved in front of a developer than the average framework.

    Frameworks aren't really like languages. All computer languages tend to be really, really similar - even outliers like Lisp have more in common with say, C, than most frameworks have with each other. If the framework you know and the framework you're learning both use a comprehensible, intelligent pattern (say, Django or CodeIgniter) you can get over the hump pretty easily. If, on the other hand, you're dealing with a steaming turd shovelled up by a decade of inbred development (say, Zend) you're not likely to be able to start coding in an hour after looking at a manual (presuming such a beast exists).

    --
    Just because you're paranoid doesn't mean there isn't an invisible demon about to eat your face