Book Image

Node.js Web Development - Fourth Edition

By : David Herron
Book Image

Node.js Web Development - Fourth Edition

By: David Herron

Overview of this book

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. 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, maintain, deploy and test your own Node.js application.You will understand the importance of transitioning to functions that return Promise objects, and the difference between fs, fs/promises and fs-extra. 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 use some well known tools to beef up security of Express 4.16 applications.
Table of Contents (19 chapters)
Title Page
Dedication
Packt Upsell
Contributors
Preface
Index

Preface

Node.js is a server-side JavaScript platform using an event-driven, non-blocking I/O model, allowing users to build fast and scalable transaction-intensive applications running in real time. It plays a significant role in the software development world and liberates JavaScript from the web browser. With Node.js, we can 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 primary focus of Node.js is developing high performance, highly scalable web applications, and it also sees a widespread use in other areas. Electron, the Node.js-based wrapper around the Chrome engine, is the basis for popular desktop applications, such as Atom and Visual Studio Code editors, GitKraken, Postman, Etcher, and the desktop Slack client. Node.js is popular for developing Internet of Things devices and sees a tremendous adoption in microservice development and for building tools for frontend web developers and more. Node.js, as a lightweight high-performance platform, fits microservice development like a glove.

The Node.js platform uses an asynchronous single-thread system, with asynchronously invoked callback functions (also known as event handlers) and an event loop, as opposed to a traditional thread-based architecture.

The theory is that threaded systems are notoriously difficult to develop, and that threads themselves impose an architectural burden on app servers. Node.js's goal is to provide an easy way to build scalable network servers.

The whole Node.js runtime is designed around asynchronous execution. JavaScript was chosen as the language because anonymous functions and other language elements provide an excellent base for implementing asynchronous computation.

Who this book is for

We assume that you have some knowledge of JavaScript and possibly have experience with server-side code development, and that you are looking for a different way of developing server-side code.

Server-side engineers may find the concepts behind Node.js refreshing. It offers a new perspective on web application development and a different take on server architectures from the monoliths we deal with in other programming languages. JavaScript is a powerful language and Node.js's asynchronous nature plays to its strengths. Having JavaScript on both the frontend and the backend gives a whole newmeaning.

Developers experienced with browser-side JavaScript will find it productive to bring that knowledge to a new territory.

Although our focus is on web application development, Node.js knowledge can be applied in other areas as well. As said earlier, Node.js is widely used to develop many types of applications.

What this book covers

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, why JavaScript should be liberated from the browser, and important recent advances in the JavaScript scene.

Chapter 2, Setting up Node.js, goes over setting up a Node.js developer environment. This includes installing Node.js on Windows, macOS, and Linux. Important tools are covered, including the npm and yarn package management systems and Babel, which is used for transpiling modern JavaScript into a form that's runnable on older JavaScript implementations.

Chapter 3, Node.js Modules, explores the module as the unit of modularity in Node.js applications. We dive deep into understanding and developing Node.js modules and using npm to maintain dependencies. We learn about the new module format, ES6 Modules, that should supplant the CommonJS module format currently used in Node.js, and are natively supported in Node.js 10.x.

Chapter 4, HTTP Servers and Clients, 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. We also learn several mitigation strategies, and have our first experience with developing REST services.

Chapter 5, Your First Express Application, begins the section on developing a note-taking application. The first step is getting a basic application running.

Chapter 6, Implementing the Mobile-First Paradigm, uses Bootstrap V4 to implement responsive web design. We take a look at integrating a popular icon set so that we can have pictorial buttons, and go over compiling a custom Bootstrap theme.

Chapter 7, Data Storage and Retrieval, ensures that we don't lose our notes when we restart the application. We explore several database engines and a method to enable easily switching between them at will.

Chapter 8, Multiuser Authentication the Microservice Way, adds user authentication to the note-taking application. Both logged-in and anonymous users can access the application, with varying capabilities based on role. Authentication is supported both for locally stored credentials and for using OAuth against Twitter.

Chapter 9, Dynamic Client/Server Interaction with Socket.IO, lets our users talk with each other in real time. JavaScript code will run in both the browser and the 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 and can leave messages/comments for others.

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 for both local development and deployment on cloud hosting services.

Chapter 11, Unit Testing and Functional Testing, takes a look at three test development models: unit testing, REST testing, and functional testing. We'll use the popular Mocha and Chai frameworks for the first two, and Puppeteer for the third. Puppeteer uses a headless version of Chrome to support running tests. Docker is used to facilitate setting up and tearing down test environments.

Chapter 12Security, explores techniques and tools required to mitigate the risk of security intrusions. Intelligently using Docker is a great first step if only because it can easily limit the attack surface of your application. The Node.js community has developed a suite of tools that integrate with Express to implement several critical security technologies.

To get the most out of this book

The basic requirement is to install Node.js and have a programmer-oriented text editor. The editor need not be anything fancy, vi/vim will even do in a pinch. We will show you how to install everything that's needed. It's all open source software that can be easily downloaded from websites. 

The most important tool is the one between your ears.

Some chapters require database engines, such as MySQL and MongoDB.

Although Node.js is a cross-platform software development platform, some third-party modules are written in C/C++ and must be compiled during installation. To do so, native-code development tools such as C/C++ compilers are required, and Python is required to run the tool-chain. The details are covered in Chapter 2, Setting up Node.js. Microsoft is involved with the Node.js project and to ensure developer productivity with Node.js on Windows.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register at www.packtpub.com.
  2. Select the SUPPORT tab.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box and follow the onscreen instructions.

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

  • WinRAR/7-Zip for Windows
  • Zipeg/iZip/UnRarX for Mac
  • 7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Node.js-Web-Development-Fourth-Edition. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The http object encapsulates the HTTP protocol, and its http.createServer method creates a whole web server, listening on the port specified in the listen method."

A block of code is set as follows:

var http = require('http'); 
http.createServer(function (req, res) { 
  res.writeHead(200, {'Content-Type': 'text/plain'}); 
  res.end('Hello World\n'); 
}).listen(8124, "127.0.0.1"); 
console.log('Server running at http://127.0.0.1:8124/'); 

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

 if (urlP.query['n']) { 
    fibonacciAsync(urlP.query['n'], fibo => {
        res.end('Fibonacci '+ urlP.query['n'] +'='+ fibo);
    });
  } else { 

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

$ node --version
v8.9.1 

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "In the Start menu, enter PowerShell in the applications search box."

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.