Node Cookbook - Fourth Edition

5 (1 reviews total)
By Bethany Griggs
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Chapter 1: Introducing Node.js 14

About this book

A key technology for building web applications and tooling, Node.js brings JavaScript to the server enabling full-stack development in a common language. This fourth edition of the Node Cookbook is updated with the latest Node.js features and the evolution of the Node.js framework ecosystems.

This practical guide will help you to get started with creating, debugging, and deploying your Node.js applications and cover solutions to common problems, along with tips to avoid pitfalls. You'll become familiar with the Node.js development model by learning how to handle files and build simple web applications and then explore established and emerging Node.js web frameworks such as Express.js and Fastify. As you advance, you'll discover techniques for detecting problems in your applications, handling security concerns, and deploying your applications to the cloud. This recipe-based guide will help you to easily navigate through various core topics of server-side web application development with Node.js.

By the end of this Node book, you'll be well-versed with core Node.js concepts and have gained the knowledge to start building performant and scalable Node.js applications.

Publication date:
November 2020
Publisher
Packt
Pages
512
ISBN
9781838558758

 

Chapter 1: Introducing Node.js 14

Node.js follows a release schedule and adopts a Long-Term Support (LTS) policy. The release schedule is based on the Semantic Versioning (https://semver.org/) standard.

The Node.js release policy states that there are two major releases of Node.js per year, one in April and one in October. Major releases include breaking or incompatible API changes, although the Node.js project does try to minimize the number and impact of breaking changes to reduce disruption to users.

Even-numbered major releases of Node.js are promoted to LTS after 6 months. Even-numbered releases are scheduled for release in April and promoted to LTS in October. LTS releases are supported for 30 months. It is recommended to use LTS versions of Node.js for production applications. The purpose of the LTS policy is to provide stability to end users and also to provide a predictable timeline of releases so that users can appropriately manage their upgrades. All LTS versions of Node.js are given codenames, named after elements. Node.js 14 has the LTS codename Fermium.

Odd-numbered major releases are released in October and are only supported for 6 months. Odd-numbered releases are expected to be used to try out new features and test the migration path, but are not generally recommended for use in production applications.

The Node.js Release Working Group has authority over the Node.js release schedule and processes. The Node.js release schedule and policy documentation can be found at https://github.com/nodejs/release.

This chapter introduces Node.js – including instructions on how to install the runtime and access the API documentation.

This chapter will cover the following recipes:

  • Installing Node.js 14 with nvm
  • Accessing the Node.js API documentation
  • Adopting new JavaScript syntax in Node.js 14
 

Technical requirements

This chapter will require access to a Terminal, a browser of your choice, and the internet.

 

Installing Node.js 14 with nvm

This book will be using Node.js 14 throughout, as it is the latest LTS release at the time of writing. Node.js 14 was released in April 2020, was promoted to LTS in October 2020 and will continue to be supported until April 2023. This recipe will cover how to install Node.js 14 using node version manager (nvm). At the time of writing, nvm is an incubation project of the OpenJS Foundation and provides an easy way to install and update Node.js versions.

Getting ready

You will need to have the appropriate permissions on your device to install nvm. This recipe assumes you're on a UNIX-like platform. If you're on Windows, it should be run under Windows Subsystem for Linux (WSL).

How to do it…

In this recipe, we're going to be installing Node.js 14 using nvm:

  1. First, we need to install nvm. nvm provides a script that handles the download and installation of nvm. Enter the following command in your Terminal to execute the nvm installation script:
    $ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.0/install.sh | bash
  2. nvm will automatically attempt to add itself to your path. Close and reopen your Terminal to ensure the changes have taken place. Then, enter the following command to list the nvm version we have installed; this will also confirm that nvm is available in our path:
    $ nvm --version
    0.37.0
  3. To install Node.js 14, we use the $ nvm install command. We can supply either the specific version we wish to install or the major version number. If we specify just the major version number, nvm will install the latest release of that major release line. Enter the following command to install the latest version of Node.js 14:
    $ nvm install 14
    Downloading and installing node v14.6.0...
    Local cache found: ${NVM_DIR}/.cache/bin/node-v14.6.0-darwin-x64/node-v14.6.0-darwin-x64.tar.gz
    Checksums match! Using existing downloaded archive ${NVM_DIR}/.cache/bin/node-v14.6.0-darwin-x64/node-v14.6.0-darwin-x64.tar.gz
    Now using node v14.6.0 (npm v6.14.6)

    Note that this command will install the latest version of Node.js 14, so your specific version install is likely to differ from that shown in the preceding output.

  4. The latest Node.js 14 version should now be installed and available in your path. You can confirm this by entering the following command:
    $ node --version
    v14.6.0
  5. nvm will also install the version of npm that is bundled with the Node.js version you have installed. Enter the following to confirm which version of npm is installed:
    $ npm --version
    6.14.6
  6. nvm makes it easy to install and switch between multiple Node.js versions. We can enter the following to install and switch to the latest Node.js 12 version:
    $ nvm install 12  
    Downloading and installing node v12.18.3...
    Local cache found: ${NVM_DIR}/.cache/bin/node-v12.18.3-darwin-x64/node-v12.18.3-darwin-x64.tar.gz
    Checksums match! Using existing downloaded archive ${NVM_DIR}/.cache/bin/node-v12.18.3-darwin-x64/node-v12.18.3-darwin-x64.tar.gz
    Now using node v12.18.3 (npm v6.14.6)
  7. Once we've got the versions installed, we can use the $ nvm use command to switch between them:
    $ nvm use 14
    Now using node v14.6.0 (npm v6.14.6)

We've installed the latest version of Node.js 14 using nvm.

How it works…

nvm is a version manager for Node.js on UNIX-like platforms and supports POSIX-compliant shells. POSIX is a set of standards for operating system compatibility, defined by the IEEE Computer Society.

In the first step of the recipe, we downloaded and executed the nvm installation script. Under the covers, the nvm install script does the following:

  1. It clones the nvm GitHub repository (https://github.com/nvm-sh/nvm) to ~/.nvm/.
  2. It attempts to add the following source lines to import and load nvm into the appropriate profile file, where the profile file is either ~/.bash_profile, ~/.bashrc, ~/.profile, or ~/.zshrc.

Should you use a profile file other than the previously named ones, you may need to manually add the following lines to your profile file to load nvm. The following lines are specified in the nvm installation documentation (https://github.com/nvm-sh/nvm#install--update-script):

export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm

Each time you install a Node.js version using $ nvm install, nvm downloads the appropriate binary for your platform from the official Node.js download server. The official Node.js download server can be accessed directly at https://nodejs.org/dist/. nvm will store all Node.js versions it has installed in the ~/.nvm/versions/node/ directory.

nvm supports aliases that can be used to install the LTS versions of Node.js. For example, you can use the $ nvm install --lts command to install the latest LTS release.

To uninstall a Node.js version, you can use the $ nvm uninstall command. To change the default Node.js version, use the $ nvm alias default <version> command. The default version is the version that will be available by default when opening your Terminal.

There's more…

If you do not wish to or are unable to use nvm, you can install Node.js manually. Visit the Node.js downloads page at https://nodejs.org/en/download/ to download the appropriate binary for your platform.

The Node.js project provides TAR files for installation on many platforms. To install via a TAR file, you need to download and extract the TAR file, and then add the binary location to your path.

Alongside TAR files, the Node.js project provides an installer for both macOS (.pkg) and Windows (.msi). As a result of installing Node.js manually, you would need to manually install updated versions of Node.js when you require them.

See also

  • The Accessing the Node.js API documentation recipe in this chapter
 

Accessing the Node.js API documentation

The Node.js project provides comprehensive API reference documentation. The Node.js API documentation is a critical resource for understanding which APIs are available in the version of Node.js that you're using. The Node.js documentation also describes how to interact with APIs, including which arguments a method accepts and the method's return value.

This recipe will show how to access and navigate the Node.js API documentation.

Getting ready

You will need access to a browser of your choice and an internet connection to access the Node.js API documentation.

How to do it…

This recipe is going to demonstrate how to navigate the Node.js API documentation:

  1. First, navigate to https://nodejs.org/api/ in your browser.

    Expect to see the Node.js API documentation for the most recent version of Node.js:

    Figure 1.1 – Node.js API documentation home page

    Figure 1.1 – Node.js API documentation home page

  2. Hover over the View another version link and expect to see the other release lines of Node.js listed. This is how you can change which version of Node.js you're viewing the documentation for:
    Figure 1.2 – Node.js API documentation showing the version dropdown

    Figure 1.2 – Node.js API documentation showing the version dropdown

  3. Now, let's suppose we want to find the documentation for the fs.readFile() method. The fs.readFile() method is exposed via the File system core module. We first need to locate and click on File system in the left-hand navigation pane. Clicking File system will take us to the table of contents for the File system core module API documentation:
    Figure 1.3 – Node.js API documentation for the File system subsystem

    Figure 1.3 – Node.js API documentation for the File system subsystem

  4. Scroll down until you find the fs.readFile() method listed in the table of contents. When looking for a specific API, it may be worthwhile using your browser's search facility to locate the API definition. Click the fs.readFile() link in the table of contents. This will open the API definition:
    Figure 1.4 – Node.js API documentation showing the fs.readFile() API definition

    Figure 1.4 – Node.js API documentation showing the fs.readFile() API definition

  5. Click <Buffer> to access the Buffer class documentation. This will detail the methods available on the Buffer type:
    Figure 1.5 – Node.js API documentation showing the Buffer class definition

    Figure 1.5 – Node.js API documentation showing the Buffer class definition

  6. Now, click Command line options in the left-hand navigation pane. This page details all the available command-line options that can be passed to the Node.js process:
Figure 1.6 – Node.js API documentation showing the available command-line options

Figure 1.6 – Node.js API documentation showing the available command-line options

We've learned how to access and navigate the Node.js API documentation.

How it works…

This Node.js API documentation is a vital reference resource when building Node.js applications. The documentation is specific to each version of Node.js. In the recipe, we accessed the documentation for the most recent version of Node.js, which is the default version of the documentation that is rendered at https://nodejs.org/api/. The following URL can be used to access the documentation for a specific version of Node.js: https://nodejs.org/docs/v14.0.0/api/index.html (substituting v14.0.0 with the specific version you wish to view the documentation for).

The API documentation details the usage of the Node.js APIs, including the following:

  • The accepted parameters and their types
  • If applicable, the value and type that the API returns

In some cases, the documentation will provide further information, including a usage example or sample code demonstrating the usage of the API.

Note that there are some undocumented APIs. Some Node.js APIs are intentionally undocumented. Some of the undocumented APIs are considered internal-only and are not intended for use outside of the Node.js core runtime.

The API documentation also details the stability of APIs. The Node.js project defines and uses the following three stability indices:

  • 0 – Deprecated: Usage of these APIs is discouraged. Warnings may be emitted upon the usage of these APIs. Deprecated APIs will also be listed at https://nodejs.org/dist/latest-v14.x/docs/api/deprecations.html.
  • 1 – Experimental: These APIs are not considered stable and may be subject to some non-backward-compatible changes. Experimental APIs are not subject to the Semantic Versioning rules. These APIs should be used with caution, especially in production environments.
  • 2 – Stable: With stable APIs, the Node.js project will try to ensure compatibility.

The Node.js documentation is maintained by the Node.js project in the Node.js core repository. Any errors or suggested improvements can be raised as issues at https://github.com/nodejs/node.

There's more…

The Node.js project maintains a CHANGELOG.md file for each release line of Node.js, detailing the individual commits that land in each release. The CHANGELOG.md file for Node.js 14 can be found at https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V14.md.

The following is a snippet from the Node.js 14 CHANGELOG.md file:

Figure 1.7 – The Node.js 14 CHANGELOG.md file

Figure 1.7 – The Node.js 14 CHANGELOG.md file

The Node.js project makes an effort to highlight the notable changes in each release. The CHANGELOG.md file denotes which commits were determined to be SEMVER-MINOR according to the Semantic Versioning standard (https://semver.org/). Entries marked as SEMVER-MINOR generally indicate feature additions. The CHANGELOG.md file will also denote when a release is considered a security release (fixing a security issue). In the case of a security release, the Notable Changes section will start with the sentence This is a security release.

For major releases, the Node.js project releases a release announcement on the Node.js Medium account that details the new features and changes. The Node.js 14 release announcement is available at https://medium.com/@nodejs/node-js-version-14-available-now-8170d384567e.

Node.js CHANGELOG.md files can be used as a reference when upgrading Node.js, to help understand what updates and changes are included in the new version.

 

Adopting new JavaScript syntax in Node.js 14

The formal specification for the JavaScript language is ECMAScript. New JavaScript features make their way into Node.js via updates to the underlying V8 JavaScript engine that the Node.js runtime is built on top of. ECMAScript has annual updates, which include new JavaScript language features and syntax.

New major versions of Node.js tend to include a significant upgrade to the V8 engine. Node.js version 14.0.0 was released with V8 version 8.1. But at the time of writing, Node.js 14 has already been updated to include V8 version 8.4.

Updated versions of V8 bring underlying performance improvements and new JavaScript language features and syntax to the Node.js runtime. This recipe will showcase a couple of the newer JavaScript language features that have been introduced in Node.js 14.

Getting ready

You will need to have Node.js 14 installed. You will also need to have access to a Terminal.

How to do it…

In this recipe, we will be using the Node.js Read Eval Print Loop (REPL) to test out the newer JavaScript features that have been made available in Node.js 14:

  1. First, let's open the Node.js REPL. Enter the following command in your Terminal:
    $ node
  2. This should open the REPL, which is an interface that we can use to execute code. Expect to see the following output:
    Figure 1.8 – Node.js REPL

    Figure 1.8 – Node.js REPL

  3. Start by entering the following command. This command will return the version of V8 that is embedded in the Node.js version you're using:
    > process.versions.v8
    '8.4.371.19-node.12'
  4. Optional chaining is one of the new JavaScript language features that are available as of Node.js 14. Optional chaining allows you to read the value of a nested property without having to check whether each preceding reference is valid. We can demonstrate this syntax in the REPL. First, we'll define a JSON object that has nested properties. Copy and paste the following into the REPL:
    const person = {
        name : 'Beth',
        dog : { name : 'Laddie' }
    };
  5. Now, we can demonstrate the optional chaining operator. The optional chaining operator is denoted by the ?. syntax. The optional chaining operator allows you to read the value of a nested property without having to check whether each preceding reference is valid. We can use the sample object to demonstrate this. First, enter the following, not using the optional chaining operator:
    > person.cat.name
    Uncaught TypeError: Cannot read property 'name' of undefined

    This fails, as expected, as the object we created does not have the property cat.

  6. Now, let's use the optional chaining operator:
    > person.cat?.name
    undefined

    Observe that we no longer experience TypeError. The optional chaining operator should be used in cases where you wish to check the value of a nested property but do not want to throw an error if a preceding property is not defined.

  7. Another new JavaScript feature that is available in Node.js 14 is the nullish coalescing operator, which is denoted by ??. The nullish coalescing operator is a logical operator that returns the right operand when the left operand is either null or undefined. This differs from the logical OR operator (||). The logical OR operator returns the right operand when the left operand is any falsy value. A falsy value is a value that is false when encountered in a Boolean context. Falsy values in JavaScript include false, 0, -0, 0n (BigInt) , "" (empty string), null, undefined, and NaN. Enter the following commands in the REPL to demonstrate the difference between the logical OR operator and the nullish coalescing operator:
    > 0 || "Hello World!"
    'Hello World!'
    > 0 ?? "Hello World!"
    0
    > null || "Hello World!"
    'Hello World!'
    > null ?? "Hello World!"
    'Hello World!' 

Using the REPL, we've explored two of the new JavaScript syntaxes that are available in Node.js 14.

How it works…

New JavaScript language features are introduced into Node.js via updates to the underlying Google Chrome V8 JavaScript engine. A JavaScript engine parses and executes JavaScript code. The embedding of the Google Chrome V8 engine in Node.js is what enables the execution of JavaScript outside of the browser. Chrome's V8 JavaScript is one of many available JavaScript engines, with Mozilla's SpiderMonkey, used in the Mozilla Firefox browser, being another leading JavaScript engine.

Every 6 weeks, a new version of Google Chrome's V8 engine is released. Node.js 14 will continue to incorporate updates into V8, provided they are Application Binary Interface (ABI)-compatible. An ABI describes how programs can interact with functions and data structures via compiled programs. It can be considered similar to a compiled version of an Application Programming Interface (API).

Once there is a release of V8 that is no longer ABI compatible, the specific release line of Node.js will be fixed on its current version of V8. However, specific V8 patches and fixes may continue to be applied directly to that Node.js release line. Node.js 12 is now fixed on V8 version 7.8, whereas Node.js 14, at the time of writing, is at V8 version 8.4.

The V8 JavaScript engine internally compiles JavaScript using Just-In-Time (JIT) compilation. JIT compilation speeds up the execution of JavaScript. While V8 is executing JavaScript, it obtains data about the code that is being executed. From this data, the V8 engine can make speculative optimizations. Speculative optimizations anticipate the upcoming code based on the code that has recently been executed. This allows the V8 engine to optimize for the upcoming code.

The V8 blog provides announcements of new V8 releases and details the new features and updates to V8. The V8 blog can be accessed at https://v8.dev/blog.

About the Author

  • Bethany Griggs

    Bethany Griggs is a Software Engineer and scrum master working within the IBM Runtime Technologies Node.js team since 2016. She is an active open-source developer and a part of the Node.js Technical Steering Committee Member

    Browse publications by this author

Latest Reviews

(1 reviews total)
Can’t recommend this book enough to other Node.is developers who seriously want to build modern web apps.

Recommended For You

Book Title
Unlock this book and the full library for FREE
Start free trial