38,39 €
Create real-time server-side applications with this practical, step-by-step guide
This book is for anybody looking for an alternative to the "P" languages (Perl, PHP, and Python), or anyone looking for a new paradigm of server-side application development. You should have at least a rudimentary understanding of JavaScript and web application development.
Node.js is a server-side JavaScript platform using an event driven, non-blocking I/O model allowing users to build fast and scalable data-intensive applications running in real time. Node.js Web Development shows JavaScript is not just for browser-side applications. It can be used for server-side web application development, real-time applications, microservices, and much more.
This book gives you an excellent starting point, bringing you straight to the heart of developing web applications with Node.js. You will progress from a rudimentary knowledge of JavaScript and server-side development to being able to create and maintain your own Node.js application. With this book you'll learn how to use the HTTP Server and Client objects, data storage with both SQL and MongoDB databases, real-time applications with Socket.IO, mobile-first theming with Bootstrap, microservice deployment with Docker, authenticating against third-party services using OAuth, and much more.
This book is a practical guide for anyone looking to develop striking and robust web applications using Node.js.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 446
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: August 2011
Second published: July 2013
Third edition: June 2016
Production reference: 1220616
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-150-3
www.packtpub.com
Author
David Herron
Reviewer
Nicholas Duffy
Commissioning Editor
Amarabha Banerjee
Acquisition Editor
Larissa Pinto
Content Development Editor
Samantha Gonsalves
Technical Editor
Vivek Pala
Copy Editor
Pranjali Chury
Project Coordinator
Sanchita Mandal
Proofreader
Safis Editing
Indexer
Mariammal Chettiyar
Graphics
Disha Haria
Production Coordinator
Manu Joseph
Cover Work
Manu Joseph
David Herron has worked as a software engineer in Silicon Valley for over 20 years. This includes companies both tiny and large. He has worked on a wide variety of projects, from an X.400 e-mail server and client application to assisting with the launch of the OpenJDK project (open source Java rocks), to Yahoo's Node.js application-hosting platform (Mojito and Manhattan), and applications to monitor solar power array performance.
While a staff engineer at Sun Microsystems, David worked as the architect of the Java SE Quality Engineering team where he focused on test automation tools, including co-developing the AWT Robot class. He was involved in open source activities related to Java, including the OpenJDK project.
Before Sun, he worked for VXtreme on software which eventually became Windows Media Player when Microsoft bought the company. At Mainsoft, David worked on a library that allowed developers to recompile Windows applications on Unix, and then participated in porting Internet Explorer to Unix. At The Wollongong Group, he worked on both e-mail client and server software and was part of several IETF working groups improving e-mail-related protocols.
David is interested in electric vehicles, world energy supplies, climate change, and environmental issues, and he is a co-founder of Transition Silicon Valley. As an online journalist, he writes about electric cars and other green technology on LongTailPipe.com after having written for PlugInCars.com. He runs a large electric vehicle discussion website on VisForVoltage.org, and he blogs about other topics, including Node.js, Drupal, and Doctor Who on DavidHerron.com. Using Node.js, he developed a Content Management System that produces static HTML websites or EPUB3 eBooks, AkashaCMS (akashacms.com).
There are many people I am grateful to.
I wish to thank my mother, Evelyn, for, well everything; my father, Jim; my sister, Patti; and my brother, Ken. What would life be without all of you?
I wish to thank my girlfriend, Maggie, for being there and encouraging me, her belief in me, her wisdom, and humor. May we have many more years of this.
I wish to thank Dr. Ken Kubota of the University of Kentucky for believing in me and giving me my first job in computing. It was six years of learning not just the art of computer system maintenance, but so much more.
I wish to thank my former employers, University of Kentucky Mathematical Sciences Department, The Wollongong Group, MainSoft, VXtreme, Sun Microsystems, Yahoo!, Recargo, Laplace Systems, and all the people I worked with in each company.
I am grateful to Ryan Dahl, the creator of Node.js, and the current Node.js core team members. They have the rare combination of wisdom and vision needed to create such a joy-filled fluid software development platform. Some platforms are just plain hard to work with, but not this one.
Nicholas Duffy has had a wide-ranging career, holding positions from analyst to business intelligence architect, to software engineer, and even golf professional. He has a passion for all things data and software engineering, specializing in data warehouse architecture, Python, and Node.js. He is a frequent contributor to open source projects and is, unfortunately, also a lifelong New York Mets fan.
You can read more about Nicholas' interests on this blog at https://medium.com/@duffn or contact him via GitHub at @duffn.
I'd like to thank my wife, Anne, and boys, Jack and Chuck, for their never ending support in whatever endeavor.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Welcome to the world of software development on the Node.js platform. This is an up-and-coming software platform that liberates JavaScript from the web browser, allowing us to reuse our JavaScript skills for general software development on a large range of systems. It runs atop the ultra-fast JavaScript engine at the heart of Google's Chrome browser, V8, and adds a fast and robust library of asynchronous network I/O modules. The Node.js community have developed a dizzyingly large body of third-party modules for nearly every conceivable purpose. While the primary focus of Node.js is high performance highly-scalable web applications, it is seeing widespread use in Internet of Things (IoT) applications, microservice development, asset build workflow for frontend engineers, and even in desktop applications like the Atom editor.
Microservices are one of the brightest ideas in computing today, and Node.js is right there as one of the best platforms for microservice development. This is doubly true when combined with Docker.
In just a few years, Node.js has gone from being a brand new "will anyone adopt it" technology to a major force in software development. It is now widely used in companies big and small, and the MEAN Stack (MongoDB, Express, AngularJS, and Node.js) has become a leading application model.
The Node.js platform was developed by Ryan Dahl in 2009 after a couple years of experimenting with web server component development in Ruby and other languages. His goal was to create an event-oriented system with a low-overhead architecture. This led Dahl toward an asynchronous single-thread system, as opposed to a more traditional thread-based architecture.
This model was chosen for simplicity, under the theory that threaded systems are notoriously difficult to develop and debug for lower overhead and for speed. Node.js's goal is to provide "an easy way to build scalable network servers." The design is similar to, and influenced by, other systems, such as Event Machine (Ruby) and the Twisted framework (Python).
JavaScript was chosen as the language because anonymous functions and other language elements provide an excellent base to implement asynchronous computation. Event handler functions are often coded in-line as anonymous functions. The Node.js runtime is ingeniously designed to support asynchronous I/O operations.
Now that ECMA Script 2016 is on the scene, new features, such as arrow functions and Promises, are coming to JavaScript engines, including Node.js. These powerful new capabilities will change JavaScript programming for the better. We now have a path toward taming some of the difficulties with asynchronous coding. The Promise object gives us a way to organize asynchronously-executed procedures in a semi-linear sequence, rather than the pyramid-shaped structures of callback functions.
The result is a platform that allows developers to not only succinctly write code of great power but to have a lot of fun while doing so.
Having JavaScript on both the server and the client (browser) lets us implement a vision dating back to the earliest days of the World Wide Web. Java's proponents first showed us dynamic stuff, powered by Java, running inside a web page. With Java on both client and server side, developers were supposed to reach nirvana. Java did not achieve success promoted by Sun Microsystems. Instead, it is JavaScript that is quickly advancing to implement that vision in a big way.
With Node.js, we have JavaScript on both the client and the server. While this probably won't help developers reach nirvana, our work is made much easier. We can use common code, common data structures, and more team members speak the same code language.
This book, Node.js Web Development, Third Edition, focuses on building web applications using Node.js. We assume that you have some knowledge of JavaScript and maybe even have server-side development experience. We will take a tour through the important concepts in order to understand Node.js programming.
To do so, we'll develop several applications, including a Note-taking application that will take several chapters to implement data storage with several database engines, user authentication, including OAuth2 against Twitter, real-time communications between users, and server deployment, including Docker. Along the way, we'll explore leading application development best practices, distributing heavy workloads to backend servers, and implementing REST microservices for multitiered architectures.
Chapter 1, About Node.js, introduces you to the Node.js platform. It covers its uses, the technological architecture choices in Node.js, its history, the history of server-side JavaScript, and why JavaScript should be liberated from the browser.
Chapter 2, Setting up Node.js, goes over setting up a Node.js developer environment. This includes installing Node.js on Windows, Mac OS X, and Linux, the command-line tools using ECMA Script 2015 features in Node.js, and the npm package management system.
Chapter 3, Node.js Modules, explores the module as the unit of modularity of Node.js applications. We dive deep into understanding and developing Node.js modules and using npm to maintain our dependency list.
Chapter 4, HTTP Servers and Clients – A Web Applications First Steps, starts exploring web development with Node.js. We develop several small webserver and client applications in Node.js. We use the Fibonacci algorithm to explore the effects of heavy-weight long-running computations on a Node.js application, as well as several mitigation strategies. This gives us our first exposure to REST-based service development.
Chapter 5, Your First Express Application, begins several chapters of developing a note-taking application. The first step is getting a basic application running.
Chapter 6, Implementing the Mobile-First Paradigm, uses the Bootstrap framework to implement responsive web design. Supporting mobile devices from the outset is a driving paradigm in modern software development.
Chapter 7, Data Storage and Retrieval, ensures that we don't lose our notes when restarting the application. We explore several database engines, and a method to make it easy to switch between them at will.
Chapter 8, Multiuser Authentication the Microservice Way, adds user authentication to the note-taking application. It can be used by both logged in and anonymous users with different capabilities for each. Authentication is supported against both a local user registry and using OAuth2 against Twitter.
Chapter 9, Dynamic Interaction between Client and Server with Socket.IO, lets our users talk to each other in real time. JavaScript code will be written in both browser and server, with Socket.IO providing the plumbing needed for real-time event exchange. Users will see notes change as they're edited by other users, or they will read and write notes that others can see.
Chapter 10, Deploying Node.js Applications, helps us understand Node.js application deployment. We look at both traditional Linux service deployment using an /etc/init script and using Docker to easily deploy an infrastructure of two databases and two Node.js services.
Chapter 11, Unit Testing, takes a look at three test development models: Unit Testing, REST testing, and functional testing. In addition to the Mocha and Chai frameworks, we use CasperJS to run automated tests in a headless browser component. Docker is used to facilitate test infrastructure deployment.
The basic requirement is to install Node.js and to have a programmer-oriented text editor. We will show you how to install everything that you need, all of which is open source software, easily downloaded from the web. The most important tool is the one between your ears.
The examples here were tested using Node.js v5.x and ECMA Script 2015 features are widely used.
Some chapters require the database engines, MySQL and MongoDB.
While Node.js supports cross-platform software development, some of the third-party modules require compilation from source code. This means that one must have C/C++ compiler tools and Python installed. The details are covered in Chapter 2, Setting up Node.js.
While this book is about developing web applications, it does not require you to have a web server. Node.js provides its own web server stack.
This book is written for any software engineer who wants the adventure that comes with a new software platform embodying a new programming paradigm.
Server-side engineers may find the concepts behind Node.js refreshing, giving you a different perspective on web application development. JavaScript is a powerful language, and Node.js's asynchronous nature plays to its strengths.
Developers experienced with JavaScript in the browser may find it fun to bring that knowledge to new territory.
We assume that you already know how to write software and have an understanding of modern programming languages such as JavaScript.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The implementation of this is in views/pageHeader.ejs."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "You now have both Log Out and ADD Note buttons."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Node.js-Web-Development-Third-Edition We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
Node.js is an exciting new platform for developing web applications, application servers, any sort of network server or client, and general purpose programming. It is designed for extreme scalability in networked applications through an ingenious combination of server-side JavaScript, asynchronous I/O, asynchronous programming, built around JavaScript anonymous functions, and a single execution thread event-driven architecture.
While only a few years old, Node.js has quickly grown in prominence to where it's playing a significant role. Companies, small and large, are using it for large-scale and small-scale projects. PayPal, for example, has converted many services from Java to Node.js.
The Node.js model is very different from common application server platforms using threads. The claim is that with the single-thread event-driven architecture, memory footprint is low, throughput is high, the latency profile under load is better, and the programming model is simpler. The Node.js platform is in a phase of rapid growth, and many are seeing it as a compelling alternative to the traditional Java, PHP, Python, Ruby on Rails, and so on, approach to building web applications.
At its heart, it is a standalone JavaScript engine with extensions making it suitable for general purpose programming and with a clear focus on application server development. Even though we're comparing Node.js to application server platforms, it is not an application server. Instead, Node.js is a programming runtime akin to Python, Go, or Java SE. There are web application frameworks and application servers written in Node.js, however. In the few years that Node.js has been available, it's quickly gained a significant role, fulfilling the prediction that it could potentially supplant other web application stacks.
It is implemented around a non-blocking I/O event loop and a layer of file and network I/O libraries, all built on top of the V8 JavaScript engine (from the Chrome web browser). At the time of writing this, Microsoft had just proposed a patch to allow Node.js to utilize the ChakraCore JavaScript engine (from the Edge web browser). The theoretical possibility of hosting the Node.js API on top of a different JavaScript engine may come true, in the due course of time. Visit https://github.com/nodejs/node-chakracore to take a look at the project.
The I/O library is general enough to implement any sort of server implementing any TCP or UDP protocol, whether it's DNS, HTTP, IRC, or FTP. While it supports developing servers or clients for any network protocol, its biggest use case is in regular websites in place of technology such as an Apache/PHP or Rails stack or to complement existing websites. For example, adding real-time chat or monitoring existing websites can be easily done with the Socket.IO library for Node.js.
A particularly intriguing combination is deploying small services using Docker into cloud hosting infrastructure. A large application can be divided into what's now called microservices and easily deployed at scale using Docker. The result fits agile project management methods since each microservice can be easily managed by a small team which collaborates at the boundary of their individual API.
This book will give you an introduction to Node.js. We presume the following:
We will cover the following topics in this chapter:
We will dive right into developing working applications and recognize that often the best way to learn is by rummaging around in working code.
Node.js is a platform for writing JavaScript applications outside web browsers. This is not the JavaScript we are familiar with in web browsers! For example, there is no DOM built into Node.js, nor any other browser capability.
Beyond its native ability to execute JavaScript, the bundled modules provide capabilities of this sort:
The network layer of Node.js is low level while being simple to use. For example, the HTTP modules allow you to write an HTTP server (or client) using a few lines of code. This is powerful, but it puts you, the programmer, very close to the protocol requests and makes you implement precisely those HTTP headers that you should return in request responses.
In other words, it's very easy to write an HTTP server in Node.js, but the typical web application developer doesn't need to work at that level of detail. For example, PHP coders assume that Apache is already there, and that they don't have to implement the HTTP server portion of the stack. The Node.js community has developed a wide range of web application frameworks such as Express, allowing developers to quickly configure an HTTP server that provides all of the basics we've come to expect—sessions, cookies, serving static files, logging, and so on—thus letting developers focus on their business logic.
Quit scratching your head already. Of course you're doing it, scratching your head and mumbling to yourself, "What's a browser language doing on the server?". In truth, JavaScript has a long and largely unknown history outside the browser. JavaScript is a programming language, just like any other language, and the better question to ask is "Why should JavaScript remain trapped inside browsers?".
Back in the dawn of the web age, the tools for writing web applications were at a fledgling stage. Some were experimenting with Perl or TCL to write CGI scripts, and the PHP and Java languages had just been developed. Even then, JavaScript saw use on the server side. One early web application server was Netscape's LiveWire server, which used JavaScript. Some versions of Microsoft's ASP used JScript, their version of JavaScript. A more recent server-side JavaScript project is the RingoJS application framework in the Java universe In other words, JavaScript outside the browser is not a new thing, even if it is uncommon.
You learned a lot in this chapter. Specifically, you saw that JavaScript has a life outside web browsers and you learned about the difference between asynchronous and blocking I/O. We then covered the attributes of Node.js and where it fits in the overall web application platform market and threaded versus asynchronous software. Lastly, we saw the advantages of fast event-driven asynchronous I/O, coupled with a language with great support for anonymous closures.
Our focus in this book is real-world considerations of developing and deploying Node.js applications. We'll cover as many aspects as we can of developing, refining, testing, and deploying Node.js applications.
Now that we've had this introduction to Node.js, we're ready to dive in and start using it. In Chapter 2, Setting up Node.js, we'll go over setting up a Node.js environment, so let's get started.
Before getting started with using Node.js, you must set up your development environment. In the following chapters, we'll use this for development and for non-production deployment.
In this chapter, we will cover the following topics:
So let's get on with it.
Node.js runs on POSIX-like operating systems, various UNIX derivatives (Solaris, for example) or workalikes (Linux, Mac OS X, and so on), as well as on Microsoft Windows thanks to extensive assistance from Microsoft. It can run on machines both large and small, including the tiny ARM devices such as the Raspberry Pi microscale embeddable computer for DIY software/hardware projects.
Node.js is now available via package management systems, limiting the need to compile and install from source.
Because many Node.js packages are written in C or C++, you must have a C compiler (such as GCC), Python 2.7 (or later), and the node-gyp package. If you plan to use encryption in your networking code, you will also need the OpenSSL cryptographic library. The modern UNIX derivatives almost certainly come with these, and Node.js's configure script, used when installing from source, will detect their presence. If you need to install them, Python is available at http://python.org and OpenSSL is available at http://openssl.org.
The preferred method for installing Node.js, now, is to use the versions available in package managers, such as apt-get, or Macports. Package managers simplify your life by helping to maintain the current version of the software on your computer, ensuring to update dependent packages as necessary, all by typing a simple command such as apt-get update. Let's go over this first.
The MacPorts project (http://www.macports.org/) has for years been packaging a long list of open source software packages for Mac OS X, and they have packaged Node.js. After you have installed MacPorts using the installer on their website, installing Node.js is pretty much this simple:
