Learning Node.js for .NET Developers - Harry Cummings - E-Book

Learning Node.js for .NET Developers E-Book

Harry Cummings

0,0
25,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Solve practical real-world problems using JavaScript and Node.js

About This Book

  • Learn the concepts of Node.js to gain a high-level understanding of the Node.js execution model
  • Build an interactive web application with MongoDB and Redis and create your own JavaScript modules that work both on the client side and server side
  • Familiarize yourself with the new features of Node.js and JavaScript with this exclusive step-by-step guide

Who This Book Is For

This book is for developers who want to learn JavaScript and Node.js. Previous experience with programming is desired, but no JavaScript or Node.js knowledge is required. The book focuses mostly on web development, such as networking, serving dynamic pages, and real-time client-server communication.

What You Will Learn

  • Understand which problems Node.js best solves
  • Write idiomatic JavaScript and Node.js code
  • Build web applications and command-line tools
  • Minimise complexity and efficiently solve difficult problems
  • Test and deploy Node.js applications
  • Work with persistent data
  • Implement real-time client-server applications
  • Integrate .NET and Node.js code

In Detail

Node.js is an open source, cross-platform runtime environment that allows you to use JavaScript to develop server-side web applications.

This short guide will help you develop applications using JavaScript and Node.js, leverage your existing programming skills from .NET or Java, and make the most of these other platforms through understanding the Node.js programming model. You will learn how to build web applications and APIs in Node, discover packages in the Node.js ecosystem, test and deploy your Node.js code, and more. Finally, you will discover how to integrate Node.js and .NET code.

Style and approach

This is a step-by-step and practical guide to Node.js for .Net developers. It covers the fundamentals relating to typical applications. The focus is on providing the practical skills required to develop applications, with a summary of the key concepts covered.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 277

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning Node.js for .NET Developers
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Why Node.js?
What is Node.js?
Understanding the Node.js execution model
Non-blocking
Event-driven
Single-threaded
Introducing the Node.js ecosystem
Why JavaScript?
A clear canvas
Functional nature
A bright future
When to use Node.js
Writing web applications
Identifying other use cases
Why now?
Summary
2. Getting Started with Node.js
Installing and running Node.js
Choosing an editor
Using an application framework
Getting started with Express
Exploring our Express application
Understanding Express routes and views
Using nodemon for automatic restarts
Creating modular applications with Express
Bootstrapping an Express application
Understanding Express middleware
Implementing error handling
Using Express middleware
Summary
3. A JavaScript Primer
Introducing JavaScript types
JavaScript primitive types
Functional object-oriented programming
Functional programming in JavaScript
Understanding scopes in JavaScript
Strict mode
Object-oriented programming in JavaScript
Programming without classes
Creating objects with the new keyword
Programming with classes
Class-based inheritance
Summary
4. Introducing Node.js Modules
Organizing your codebase
JavaScript module systems
Creating modules in Node.js
Declaring a module with a name and its own scope
Defining functionality provided by the module
Importing a module into another script
Defining a directory-level module
Implementing an Express middleware module
Summary
5. Creating Dynamic Websites
Handling user-submitted data
Communicating via Ajax
Implementing other data operations
Listing data in views
Issuing a delete request from the client
Splitting up Express views using partials
Summary
6. Testing Node.js Applications
Writing a simple test in Node.js
Structuring the codebase for tests
Writing BDD-style tests with Mocha
Resetting state between tests
Using Chai for assertions
Creating test doubles
Creating test doubles using Sinon.JS
Testing an Express application
Simplifying tests using SuperAgent
Full-stack testing with PhantomJS
Summary
7. Setting up an Automated Build
Setting up an integration server
Setting up a public GitHub repository
Building a project on Travis CI
Automating the build process with Gulp
Running tests using Gulp
Checking code style with ESLint
Automatically fixing issues in ESLint
Running ESLint from Gulp
Gathering code coverage statistics
Running integration tests from Gulp
Summary
8. Mastering Asynchronicity
Using the callback pattern for asynchronous code
Exposing the callback pattern
Consuming asynchronous interfaces
Writing cleaner asynchronous code using promises
Implementing promise-based asynchronous code
Consuming the promise pattern
Parallelising operations using promises
Combining asynchronous programming patterns
Summary
9. Persisting Data
Introducing MongoDB
Why choose MongoDB?
Object modeling
JavaScript
Scalability
Getting started with MongoDB
Using the MongoDB shell
Using MongoDB with Express
Persisting objects with Mongoose
Isolating persistence code
Dependency injection in Node.js
Providing dependencies
Running database integration tests on Travis CI
Introducing Redis
Why use Redis?
Installing Redis
Using Redis as a key-value store
Storing structured data in Redis
Building a user ranking system with Redis
Using Redis from Node.js
Testing with redis-js
Implementing user rankings with Redis
Making use of the users service
A note on security
Summary
10. Creating Real-time Web Apps
Understanding options for real-time communication
Introducing Socket.IO
Implementing a chat room with Socket.IO
Scaling real-time Node.js applications
Using Redis as a backend
Integrating Socket.IO with Express
Directing Socket.IO messages
Testing Socket.IO applications
Organizing Socket.IO applications
Exposing real-time updates to the model
Organizing Socket.IO applications using namespaces
Partitioning Socket.IO clients using rooms
Summary
11. Deploying Node.js Applications
Working with Heroku
Setting up a Heroku account and tooling
Running an application locally with Heroku
Deploying an application to Heroku
Working with Heroku logs, config, and services
Setting up MongoDB
Setting up Redis
Deploying from Travis CI
Setting encrypted Travis CI environment variables
Installing Ruby
Creating an encrypted environment variable
Further resources
Summary
12. Authentication in Node.js
Introducing Passport
Choosing an authentication strategy
Understanding third-party authentication
Using Express sessions
Specifying a session secret
Deciding when the session gets saved
Using alternative session stores
Using session middleware
Implementing social login
Setting up a Twitter application
Configuring Passport
Persisting user data with Redis
Configuring Passport with persistence
Hiding functionality from unauthenticated users
Integration testing with Passport
Allowing users to log out
Adding other login providers
Summary
13. Creating JavaScript Packages
Writing universal modules
Comparing Node.js and RequireJS
Supporting the browser environment
Using AMD modules with RequireJS
Isomorphic JavaScript
Writing npm packages
Defining an npm package
Publishing a package to npm
Running automated clients on the web
Releasing a standalone tool to npm
Using Node.js modules in the browser
Controlling Browserify's output
Summary
14. Node.js and Beyond
Understanding Node.js versioning
A brief history of Node.js
Introducing the Node.js LTS schedule
Understanding ECMAScript versioning
Exploring ECMAScript 2015
Understanding ES2015 modules
Using syntax improvements from ES2015
The for... of loop
The spread operator and rest parameters
Destructuring assignment
Introducing generators
Introducing ECMAScript 2016
Going beyond JavaScript
Exploring compile-to-JavaScript languages
TypeScript
CoffeeScript
And beyond...
Introducing a true assembly language for the web
Understanding asm.js
Understanding WebAssembly
JavaScript and ASP.NET
Exploring .NET Core
Defining project structure in .NET Core
Managing dependencies in .NET Core
Building web applications in ASP.NET Core
Integration with JavaScript
Server-side JavaScript integration with .NET
Summary
Index

Learning Node.js for .NET Developers

Learning Node.js for .NET Developers

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: June 2016

Production reference: 1170616

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78528-009-2

www.packtpub.com

Credits

Author

Harry Cummings

Reviewer

David Simons

Commissioning Editor

Kunal Parikh

Acquisition Editor

Rahul Nair

Content Development Editor

Trusha Shriyan

Technical Editor

Jayesh Sonawane

Copy Editor

Safis Editing

Project Coordinator

Kinjal Bari

Proofreader

Safis Editing

Indexer

Mariammal Chettiyar

Graphics

Disha Haria

Production Coordinator

Nilesh Mohite

Cover Work

Nilesh Mohite

About the Author

Harry Cummings has been working in software development for 8 years, and for the past few years, he has performed the role of technical lead across a variety of projects for varied clients. He has, in the past, also worked as a developer, project manager, and consultant. This gives him an excellent all-round view of the role of a technical lead and its relationship with other roles as well as insight into every stage of project delivery, from initial analysis to long-term maintenance.

Harry has extensive experience in C#/.NET, Java and Scala, and JavaScript/Node.js. He continues to work directly with these technologies on a regular basis in the teams that he leads. His broader interests and expertise lie in sharing and nurturing software development best practices through training and mentoring. He has appeared at conferences such as NDC London and SDD Conf, speaking about diverse topics, ranging from introductory Node.js through to automated test strategies and long-term project maintainability.

About the Reviewer

David Simons is a London-based software consultant. He is familiar with a wide range of tools, having helped clients such as the BBC and News International deliver web solutions in a range of languages, including .NET, Java, and full-stack JavaScript. He shares his insights around these and his background in statistics research at a range of conferences, including NDC and JSConf.

As of 2016, he works with London-based consultancy GraphAware to advocate and consult on the use of graph databases in modern applications.

www.PacktPub.com

eBooks, discount offers, and more

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.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

The purpose of this book is to help .NET or Java developers make the leap to Node.js. You may have some web development experience, and perhaps you've written some browser-based JavaScript in the past. It might not be obvious why anyone would want to take JavaScript out of the browser and use it for server-side development. However, this is exactly what Node.js does. What's more, Node.js has been around for long enough now to have matured as a platform, and has sustained its impressive growth in popularity well beyond any period that could be attributed to initial hype over a new technology.

The first objective of this book then is to explain why Node.js is a compelling technology that's worth learning more about. The first few chapters introduce Node.js with this in mind, quickly get you up and running with Node.js, and provide an important (re) introduction to the JavaScript language to set you on the right track.

The main part of this book will then take you through a worked example of building up a Node.js web-application step by step. In the process, we'll illustrate all the important tools and techniques required for real-world development projects in Node.js. The aim is to make the most of your existing development expertise to allow you to quickly reach the same level of best practices and professionalism with Node.js.

The final chapters of the book show how to use Node.js for other purposes outside of web applications and how to continue learning Node.js and exploring the ecosystem around it. We'll also see how you can use Node.js alongside .NET and benefit from applying your programming skills across both technologies.

What this book covers

Chapter 1, Why Node.js?, introduces Node.js as a programming platform. It covers the execution model of Node.js, particularly how it differs from .NET and Java, and the use cases in which these differences become strengths. This chapter also discusses the suitability of JavaScript as a development language.

Chapter 2, Getting Started with Node.js, dives straight into creating a Node.js application. In this chapter, you will install Node.js, choose a code editor, and set up a minimal web application project. You'll also learn some important command-line tools for working with Node.js.

Chapter 3, A JavaScript Primer, introduces the most important things to know when programming in JavaScript. It describes the JavaScript type system and its particular flavor of functional object-oriented programming, including prototype-based inheritance. This chapter also covers a few key gotchas and JavaScript language quirks.

Chapter 4, Introducing Node.js Modules, explains how to structure JavaScript applications using modules. It introduces the Node.js module system and shows you how to use this to organise your application's code.

Chapter 5, Creating Dynamic Websites, expands on the examples from the previous chapter to build a functioning web application. You'll add a JSON API and dynamic views to your application and communicate between the client and server using Ajax.

Chapter 6, Testing Node.js Applications, shows you how to write automated tests in JavaScript and Node.js. It introduces a number of tools and libraries for writing and running tests in JavaScript, and guides you through writing a variety of unit tests and integration tests for your application.

Chapter 7, Setting up an Automated Build, covers build automation and continuous integration in Node.js. You'll set up a CI server and task runner for your application, adding automated tasks to run tests, execute static analysis, and assess code coverage.

Chapter 8, Mastering Asynchronicity, introduces different patterns for asynchronous programming in JavaScript. You'll apply these to your own application and make the most of JavaScript language features and libraries for simplifying asynchronous code.

Chapter 9, Persisting Data, explains persistent data stores that can be used with Node.js. It introduces MongoDB and Redis, explaining their different data models and their use cases. You'll integrate both of these data stores with your Node.js application.

Chapter 10, Creating Real-time Web Apps, shows how to implement real-time two-way communication between the client and the server. You'll use the Socket.IO library to add real-time functionality into your application. You'll also see how to write tests for this functionality and how to write scalable real-time applications using Redis as a backend.

Chapter 11, Deploying Node.js Applications, demonstrates how to get a Node.js application onto the Web. You'll deploy your application to a free cloud-hosting provider. You'll see how to configure data stores and how to use remote server logs for debugging.

Chapter 12, Authentication in Node.js, covers authentication for Node.js web applications. You'll implement authentication using third-party providers, integrate this with your application, and show different content to logged-in and logged-out users.

Chapter 13, Creating JavaScript Packages, explains how to create standalone JavaScript packages for use by others. You'll see how to write universal JavaScript libraries that can run on both the client and the server, and how to write a standalone command-line application using Node.js.

Chapter 14, Node.js and Beyond, puts the content of this book in a wider context. It explains how Node.js and JavaScript are continuing to evolve, so you can be prepared for and take advantage of upcoming changes. It covers some alternative programming languages for Node.js and the Web, and how these relate to JavaScript. It discusses how some of the principles from Node.js can be applied to .NET programming, and illustrates how these are particularly visible in .NET Core (the new version of .NET). It also shows how you can use Node.js together with .NET to gain the best of both worlds.

What you need for this book

All of the tools and services used in this book are available for free online. Most of the worked examples require an active web connection at some point. To get started, you need nothing more than a console, a web browser, and permission to install new software on your machine. To support developers coming from a .NET background, some of the console listings or example steps in this book use Windows conventions (for example, backslashes in paths). None of the examples depend on Windows specifically though. You can work through this book on Windows, Mac OSX, or Linux.

Who this book is for

This book is for .NET or Java developers who are interested in learning Node.js. No prior experience with Node.js is expected. You might have written some client-side JavaScript before, but this is not required. The main worked example in this book is a Node.js web application. Web development experience in .NET or Java will be helpful, but it's not necessary to have experience with any particular application library or framework.

Conventions

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: "ES2015 introduces the let keyword for declaring variables."

A block of code is set as follows:

<!DOCTYPE html> <html> <head> <title>{{ title }}</title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1>{{ title }}</h1> <p>Welcome to {{ title }}</p> </body> </html>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

/* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express', name: 'World' }); });

Any command-line input or output is written as follows:

> npm install –g nodemon

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: "Clicking the Next button moves you to the next screen."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

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.

Customer support

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.

Downloading the example code

You can download the example code files for this book from https://github.com/NodeJsForDevelopers and also 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:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

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.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/LearningNodejsForNETDevelopers_ColorImages.pdf.

Errata

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

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.

Questions

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.

Chapter 1. Why Node.js?

Node.js is still relatively new compared to platforms such as .NET and Java, but has become very popular in a short time, and has even started influencing these platforms. This is thanks to its distinctive programming model, extensive ecosystem, and powerful tooling.

These factors make Node.js a compelling alternative to other platforms. They can also make it intimidating. Its distinctive programming model may seem quite alien compared to other platforms. The sheer range of available libraries and tools can be bewildering.

This book will guide you through Node.js so you can start using it in your applications. It will help you to understand Node.js, navigate its ecosystem, and leverage your existing development skills in this new environment.

In this chapter, we will cover the following topics:

Introducing the Node.js platformSeeing how its execution model worksExploring the Node.js ecosystemLooking at JavaScript as a language choiceConsidering the range of use cases for Node.js

What is Node.js?

Node.js consists of a JavaScript engine together with low-level APIs for core server-side functionality. The execution engine is the same V8 engine developed for the Chrome web browser. Node.js takes this engine and embeds it in a standalone application that can run JavaScript outside the browser.

In Node.js, the standard APIs found in browsers to support client-side web development, such as the Document Object Model(DOM) and XMLHttpRequest, are not present. Instead, there are APIs to support general-purpose application development. These core APIs cover low-level functionality such as the following:

Networking and securityAccessing the file systemDefining and requiring modulesRaising and consuming eventsHandling binary data streamsCompressionUTF-8 supportRetrieving basic information about the OSManaging child processes

Some of these APIs may already be familiar from developing client-side JavaScript. For example, the Timers API exposes the familiar setTimeout and setInterval functions.

Node.js also provides several tools to help with the development process. These include console logging, debugging, a Read-Eval-Print Loop (REPL) (or interactive console), and basic assertions for testing.

Understanding the Node.js execution model

The execution model of Node.js follows that of JavaScript in the browser. It is quite different from that of most general-purpose programming platforms.

Stated formally, Node.js has a single-threaded, non-blocking, event-driven execution model. We will define each of these terms in this section.

Non-blocking

Put simply, Node.js recognizes that many programmes spend most of their time waiting for other things to happen, for example, slow I/O operations such as disk access and network requests.

Node.js addresses this by making these operations non-blocking. This means that program execution can continue while they happen. For example, the filesystem API's stat function for retrieving statistics about a file may be called as follows:

fs.stat('/hello/world', function (error, stats) { console.log('File last updated at: ' + stats.mtime); });

Two arguments are passed to the fs.stat function: the name of the file that we are interested in, and a callback function. The fs.stat call returns immediately, returning control of execution to the current thread but not returning a value. If there are further commands following the fs.stat call, these will then be executed. Otherwise, the thread is released to perform other work. The callback function is invoked (that is 'called back') only after the runtime has finished communicating with the filesystem. The result of the filesystem operation is passed into the callback function.

This non-blocking approach is also called asynchronous programming. Other platforms support this (for example, C#'s async/await keywords and .NET's Task Parallel Library). However, it is baked in to Node.js in a way that makes it simple and natural to use. Asynchronous API methods are all called in the same way as fs.stat. They all take a callback function that gets passed error and result arguments.

Event-driven

The event-driven nature of Node.js describes how operations are scheduled. In typical procedural environments, a program has an entry point that executes a set of commands until completion, or enters a loop and performs some processing on each iteration.

Node.js has a built-in event loop, which isn't exposed to the developer. It is the job of the event loop to decide which piece of code to execute next. Typically, this will be a callback function that is ready to run in response to some other event. For example, a filesystem operation may have completed, a timeout may have expired, or a new network request may have arrived.

This built-in event loop simplifies asynchronous programming by providing a consistent approach and avoiding the need for applications to manage their own scheduling.

Single-threaded

The single-threaded nature of Node.js simply means that there is only one thread of execution in each process. Also, each piece of code is guaranteed to run to completion without being interrupted by other operations. This greatly simplifies development and makes programs easier to reason about. It removes the possibility for a range of concurrency issues. For example, it is not necessary to synchronize/lock access to shared in-process state as it is in Java or .NET. A process can't deadlock itself or create race conditions within its own code. Single-threaded programming is only feasible if the thread never gets blocked waiting for long-running work to complete. Thus, this simplified programming model is made possible by the non-blocking nature of Node.js.

Introducing the Node.js ecosystem

The built-in Node.js APIs provide a low-level core for creating applications. Applications typically only use a small number of these APIs directly. They often use third-party library modules that provide higher-level abstractions for application development.

Node.js has its own package manager, npm. This is similar to .NET's NuGet or the package management aspects of Java's Maven. Applications specify their dependencies in a simple JSON file.

The npm registry provides a central repository for packages. This registry has grown rapidly and is already much larger (in terms of number of available packages) than the corresponding repositories for other platforms (see http://www.modulecounts.com/). There are hundreds of thousands of packages available, providing a vast array of functionality.

The npm command line tool can be used to download packages and install new ones. Library dependencies are installed locally to each application. Some packages provide command-line tools, which may be installed globally rather than under a specific project.

Many frameworks available on npm are split into a small extensible core and a number of composable modules. This approach makes it easy to understand the libraries on which your application depends, avoiding the need to reason about complex heavyweight frameworks.

The consistency of calling non-blocking (asynchronous) API methods in Node.js carries through to its third-party libraries. This consistency makes it easy to build applications that are asynchronous throughout.

Why JavaScript?

JavaScript is a language that can seem unintuitive compared to other popular object-oriented (OO) languages. It also has a number of quirks and flaws that have drawn criticism (and occasional ridicule). It might then seem a surprising choice of language for a new programming platform. This section discusses the factors that make JavaScript a more appealing choice.

A clear canvas

The size and complexity of JavaScript is part of its appeal. The core language itself, which doesn't include APIs such as the DOM, is small and simple. This makes it easy for Node.js to establish its own styles and conventions.

The new APIs provided by Node.js and the consistent approach to asynchronous programming wouldn't be possible in a more complex language with a larger pre-existing standard class library.

Functional nature

JavaScript was first built as a programming language for client-side functionality in the browser. This might not make it an obvious choice for general-purpose programming.

In fact, these two use cases do have something important in common. User interface code is naturally event-driven (for example, binding event handlers to button clicks). Node.js makes this a virtue by applying an event-driven approach to general-purpose programming.

JavaScript supports functions as first-class objects. This means it's easy to create functions dynamically and pass around references to them. This fits in well with the asynchronous, non-blocking approach of Node.js. In particular, it's easy to expose and use APIs based around callback functions.

A bright future

JavaScript has received a lot of attention in the last several years as it has become more widely used for providing rich functionality on the Web. Browser vendors have put a huge amount of engineering effort into improving the performance of JavaScript. Node.js benefits from this directly via its use of Chrome's V8 engine.

The JavaScript language itself is undergoing some major changes for the better. The ECMAScript 2015 standard (previously known as ES6) represents the most significant revision of the language in its history. It introduces features that make the language more intuitive and less verbose. It also addresses flaws that JavaScript has been criticized for in the past, removing gotchas and making programs easier to reason about.

When to use Node.js

As discussed earlier in this chapter, Node.js recognizes that I/O is a bottleneck for many applications. On most programming platforms, threads will waste time blocking on I/O operations. There are approaches developers can take to avoid this, but these all involve adding some complexity to their code. In Node.js, the platform itself provides a completely natural approach.

Writing web applications

The flagship use case for Node.js is building web applications. These are inherently event-driven as most or all processing takes place in response to HTTP requests. Also, many websites do little computational heavy-lifting of their own. They tend to perform a lot of I/O operations:

Streaming requests from the clientTalking to a database, locally or over the networkPulling in data from remote APIs over the networkReading files from disk to send back to the client

These factors make I/O operations a likely bottleneck for web applications. The non-blocking programming model of Node.js allows web applications to make the most of a single thread. As soon as any of these I/O operations starts, the thread is immediately free to pick up and start processing another request. Processing of each request continues via asynchronous callbacks when I/O operations complete. The processing thread is only kicking off and linking together these operations, never waiting for them to complete. This allows Node.js to handle a much higher rate of requests per thread than other platforms. You can also still make use of multiple threads (for example, on multi-core CPUs) by simply running multiple instances of the Node.js process.

Identifying other use cases

There are of course some applications that don't perform much I/O and are more likely to be CPU bound. Node.js would be less suitable for computationally-intensive applications. Programs that do a lot of processing of in-memory data are less concerned about I/O.

Web applications are not the only I/O-heavy applications though. Other classes of program that could be a good candidate for Node.js include the following:

Tools that manipulate large amounts of data on diskSupervisor programs coordinating other software or hardwareNon-browser GUI applications that need to respond to user input

Node.js is especially suitable for glue applications that pull together functionality from other remote services. The increasing popularity of microservices as an architectural pattern makes this kind of application more common.

Why now?

Node.js has been around for several years, but now is the perfect time to start using it if you haven't already.

The release of Node.js v4 towards the end of 2015 consolidated the project's governance model and heralds Node.js coming to maturity. It also allows the project to keep more up to date with the V8 engine. This means that Node.js can benefit more directly from ongoing development on V8. For example, security and performance improvements to V8 will now make their way into Node.js much sooner.

As discussed earlier in this chapter, the release of the ECMAScript 2015 standard makes JavaScript a much more appealing language. It pulls in useful features from other popular OO languages and resolves a number of long-standing flaws in JavaScript.

Meanwhile, the ecosystem of third party libraries and tools around Node.js and JavaScript continues to grow. Node.js is treated as a first-class citizen by major hosting platforms. Companies such as Google and Microsoft are also throwing their weight behind JavaScript and related technologies.