Smashing Node.js Javascript Everywhere
Guillermo Rauch
This edition first published 2012 2012 Guillermo Rauch Registered office John Wiley & Sons Ltd, The Atrium, Southern Gate, Chichester, West Sussex, PO19 8SQ, United Kingdom For details of our global editorial offices, for customer services and for information about how to apply for permission to reuse the copyright material in this book please see our website at www.wiley.com. The right of the author to be identified as the author of this work has been asserted in accordance with the Copyright, Designs and Patents Act 1988. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, except as permitted by the UK Copyright, Designs and Patents Act 1988, without the prior permission of the publisher. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
Designations used by companies to distinguish their products are often claimed as trademarks. All brand names and product names used in this book are trade names, service marks, trademarks or registered trademarks of their respective owners. The publisher is not associated with any product or vendor mentioned in this book. This publication is designed to provide accurate and authoritative information in regard to the subject matter covered. It is sold on the understanding that the publisher is not engaged in rendering professional services. If professional advice or other expert assistance is required, the services of a competent professional should be sought.
Trademarks: Wiley and the John Wiley & Sons, Ltd. logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and/or other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. John Wiley & Sons, Ltd. is not associated with any product or vendor mentioned in the book.
A catalogue record for this book is available from the British Library. ISBN 978-1-119-96259-5 (paperback); ISBN 978-1-119-96311-0 (emobi);
978-1-119-96309-7 (epdf); 978-1-119-96310-3 (epub) Set in 10/12 Minion Pro Printed in the U.S. at Command Web Publishers Acknowledgements Some of the people who helped bring this book to market include the following: Editorial and Production VP Consumer and Technology Publishing Director: Michelle Leete Associate DirectorBook Content Management: Martin Tribe Associate Publisher: Chris Webb Assistant Editor: Ellie Scott Development Editor: Brian Herrmann Copy Editor: Chuck Hutchinson Technical Editor: Goddy Zhao Editorial Manager: Jodi Jensen Senior Project Editor: Sara Shlaer Editorial Assistant: Leslie Saxman Marketing Associate Marketing Director: Louise Breinholt Senior Marketing Executive: Kate Parrett Composition Services Compositor: Andrea Hornberger Proofreader: Linda Seifert Indexer: Potomac Indexing, LLC About the Author Guillermo Rauch (San Francisco, CA) is CTO and co-founder of San Francisco-based education startup LearnBoost. Rauch is the inventor of several renowned Node.JS projects, and has been a speaker at JSConf as well as Node.js workshops.
Foreword Most web applications have both a client side and a server side. Implementing the server side has traditionally been complex and cumbersome.
Creating a simple server required expert knowledge about multi-threading, scalability, and server deployment. An additional complication is that web client software is implemented using HTML and JavaScript whereas server code most often is implemented using more static programming languages. This split forces the programmer to use multiple programming languages and make early design decisions about where certain program logic should reside. A few years ago, it would have been unthinkable to implement server software in JavaScript. Poor runtime performance, toy-like memory management, and lack of operating system integration all had to be fixed before JavaScript could be considered as a viable solution for servers. As part of Google Chrome, we designed the new V8 JavaScript engine to tackle the first two problems.
V8 is available as an open source project with a simple API for embedding. Ryan Dahl saw the opportunity in bringing JavaScript to the server side by embedding V8 into an OS integration layer that featured asynchronous interfaces to the underlying operating system. That was the inception of Node.JS. The benefits were obvious. Programmers could now use the same programming language on both client and server side. The dynamic nature of JavaScript made it trivial to develop and experiment with server code freeing the programmer from the traditional slow tool-heavy programming model.
Node.JS became an instant success, spawning a vibrant open source community, supporting companies, and even necessitating its own conference. I would attribute this success to a combination of simplicity, improved programming productivity, and high performance. Im pleased V8 played a small part in this. This book will take the reader through all steps of creating the server side of a web application on top of Node.JS including how to organize asynchronous server code and interface to databases. Enjoy the book, Lars Bak, Virtual Machinist Introduction Late in 2009, Ryan Dahl announced a technology named Node.JS (http://nodejs.org/) at a JavaScript conference in Berlin. Interestingly, and to the surprise of the attendees, this technology wasnt designed to run in the browser, the land that JavaScript had conquered and that many developers thought it would always be confined to.
This technology was about running JavaScript in the server . That simple phrase immediately sparked the imagination of the audience, which celebrated the announcement in standing ovation. If done right, we could write web applications in just one language. That was, undoubtedly, the first thought in everyones minds. After all, to produce a rich and modern web application, one must be proficient with JavaScript, but server technologies are varied and require specialization. As an example, Facebook recently revealed that its codebase has four times the number of lines of JS than PHP, its back-end language of choice.
But what Ryan was interested in showing went beyond that simple yet powerful premise. Ryan showed that the hello world program of Node.JS creates a web server: var http = require(http);
var server = http.createServer(function (req, res) {
res.writeHead(200);
res.end(Hello world);
});
server.listen(80);
It so happens this webserver is not just a toy, but a high-performance web server that happens to fare just as well (or even better) than established and tested software like Apache and Nginx in a multitude of scenarios. Node.JS was presented as a tool specifically aimed to design network applications the right way . Node.JS owes its incredible speed and performance to a technique called the event loop and the fact that it runs on top of V8, the JavaScript interpreter and virtual machine that Google created to make their Chrome web browser run impossibly fast. When it comes to web development, Node.JS changes the panorama. You are no longer writing scripts that are executed by a web server you install separately, such as the traditional LAMP model, which usually involves PHP and Apache.