Explore 1.5M+ audiobooks & ebooks free for days

Only $12.99 CAD/month after trial. Cancel anytime.

Node.js: Novice to Ninja
Node.js: Novice to Ninja
Node.js: Novice to Ninja
Ebook638 pages4 hours

Node.js: Novice to Ninja

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Node.js: Novice to Ninja is your hands-on guide to learning everything needed to build a professional web application using Node.js, the hugely popular open-source, cross-platform, back-end JavaScript runtime environment. You'll start off by getting familiar with the basics - installation and building your first apps - before moving onto more advanced concepts, including debugging, asynchronous programming, using Express.js, working with databases, deployment, and more. You'll finish by building a complete multi-player real-time quiz application.

  • Install Node and build your first application
  • Get started with Express.js and use it to process forms
  • Master asynchronous programming in Node.js
  • Work with MongoDB and MySQL databases
  • Use WebSockets for real-time applications
  • Understand the Node ecosystem: npm and modules
  • Build a complete multiplayer quiz app
  • And much more!

The book includes access to 25 high quality tutorial videos, containing 1.5 hours of content.

LanguageEnglish
PublisherSitePoint
Release dateJun 7, 2022
ISBN9781098141011
Node.js: Novice to Ninja
Author

Craig Buckler

Craig is a UK-based freelance full-stack web developer, writer, and speaker who's passionate about standards and performance. He began coding in the 1980s and started client-side JavaScript development on its release in 1995 when DHTML, spacer GIFs, and marquees were considered sophisticated. You may have encountered his work at SitePoint, where he's written more than 1,200 tutorials, and books including Jump Start Web Performance, Browser DevTool Secrets, and Docker for Web Developers. Craig used Node.js from the start and hopes this book is a great first step on your server-side JavaScript journey. Contact him on Twitter @craigbuckler or at craigbuckler.com.

Read more from Craig Buckler

Related to Node.js

Related ebooks

Programming For You

View More

Reviews for Node.js

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Node.js - Craig Buckler

    Preface

    This book will help you get started with Node.js in the shortest possible time. Within a day or two you should have enough knowledge to write simple applications.

    Prerequisites

    This book is for web developers taking their first steps with Nodes.js. Ideally, you should understand web development concepts and technologies:

    web browsers (client-side HTML, CSS, and JavaScript)

    web servers (code to serve web pages and APIs)

    It will help if you already know some JavaScript—perhaps from writing client-side scripts. This book explains some aspects of JavaScript in relation to Node.js, but you won’t find deep dives into variables, loops, functions, objects, and so on.

    A little knowledge of the command line, Git, and code editors such as VS Code will also be useful.

    Conventions Used

    Code Samples

    Code in this book is displayed using a fixed-width font, like so:

    A Perfect Summer's Day

    It was a lovely day for a walk in the park.

    The birds were singing and the kids were all back at school.

    Some lines of code should be entered on one line, but we’ve had to wrap them because of page constraints. An ➥ indicates a line break that exists for formatting purposes only, and should be ignored:

    URL.open("https://www.sitepoint.com/responsive-web-

    ➥design-real-user-testing/?responsive1");

    You’ll notice that we’ve used certain layout styles throughout this book to signify different types of information. Look out for the following items.

    Tips, Notes, and Warnings

    Hey, You!

    Tips provide helpful little pointers.

    Ahem, Excuse Me ...

    Notes are useful asides that are related—but not critical—to the topic at hand. Think of them as extra tidbits of information.

    Make Sure You Always ...

    ... pay attention to these important points.

    Watch Out!

    Warnings highlight any gotchas that are likely to trip you up along the way.

    Where to Find Help

    PHP and MySQL are moving targets, so chances are good that, by the time you read this, some minor detail or other of these technologies has changed from what’s described in this book. Thankfully, SitePoint has a thriving community of PHP developers ready and waiting to help you out if you run into trouble, and we also maintain a list of known errata for this book you can consult for the latest updates.

    The SitePoint Forums

    The SitePoint Forums are discussion forums where you can ask questions about anything related to web development. You may, of course, answer questions, too. That’s how a discussion forum site works—some people ask, some people answer, and most people do a bit of both. Sharing your knowledge benefits others and strengthens the community. A lot of fun and experienced web designers and developers hang out there. It’s a good way to learn new stuff, have questions answered in a hurry, and just have fun.

    The SitePoint Forums include separate forums for PHP and MySQL:

    PHP

    Databases & MySQL

    The Code Archive

    As you progress through this book, you’ll note a number of references to the code archive. This is a GitHub repository that contains each and every line of example source code that’s printed in this book. If you want to cheat (or save yourself from carpal tunnel syndrome), go ahead and download the archive. Select the example from the dropdown that says Branch, then choose Clone or Download, and you can download a .zip file for that example.

    Alternatively, if you’re familiar with Git, you can clone the repository.

    Your Feedback

    If you’re unable to find an answer through the forums, or if you wish to contact us for any other reason, the best place to write is [email protected]. We have a well-staffed email support system set up to track your inquiries, and if our support team members are unable to answer your question, they’ll send it straight to us. Suggestions for improvements, as well as notices of any mistakes you may find, are especially welcome. You can also report and discuss issues in the book’s GitHub repository.

    Let’s Go

    Now that I’ve introduced myself, given you some broad tips, and shown you where to find help, it’s time to get started! You’ll begin by setting up a development environment, and you’ll be writing your first lines of code very shortly.

    Chapter 1: What is Node.js

    Node.js is a JavaScript runtime, which means it runs programs written in JavaScript. Most developers use it to create command-line tools or web server applications.

    Skip Ahead?

    That’s everything you need know about Node.js. If you’re eager to start programming, skip ahead to Chapter 2. That said, it’s worth revisiting this chapter later to learn about Node’s advantages and core features.

    JavaScript, JScript, ECMAScript, ES6, ES2015?

    To make learning more confusing for beginners, JavaScript has many names. It started life as Live Script in 1994. Netscape rebranded it as JavaScript following a hasty deal with Sun Microsystems, despite it bearing little resemblance to Java or lightweight scripting. Microsoft couldn’t use that name, so it became JScript in Internet Explorer.

    In 2005, Mozilla (which grew out of Netscape) joined ECMA International and standardized the language as "ECMAScript". Versions 1 to 3 documented the evolution of JavaScript up until 1999. Version 4 was abandoned, but ECMAScript 5 became the standard supported by most browsers in 2009.

    Work then started on ECMAScript 6—or ES6. The final specification was approved in 2015, which led to yet another name: ES2015. New specifications now arrive every year.

    Rightly or wrongly, this course refers to JavaScript throughout. References to specific versions (such as ES9/ES2018) are only made if they affect the version of Node.js you need to use.

    Node.js was initially developed by Ryan Dahl. He took the V8 JavaScript engine from Google’s Chrome browser, added some APIs, wrapped it in an event loop, and launched it as an open-source product on Linux and macOS in 2009. The Windows edition arrived in 2011.

    The Node Package Manager (npm) was introduced in 2010. It allowed developers to use code modules published by others in their own projects. There was no official ECMAScript module standard at the time, so Node.js and npm adopted CommonJS.

    The first (non-beta) release of Node.js arrived in 2015, with updates promised every six months.

    Node.js wasn’t the first JavaScript runtime, but unlike other options—such as Rhino and SpiderMonkey—its popularity grew exponentially. Even those writing PHP, Python, Ruby or other languages often use Node.js tools to supplement their development processes.

    Why Learn Node.js?

    JavaScript is the most-used language on GitHub, and it’s ranked highly by developers. Companies including Netflix, Uber, Trello, PayPal, LinkedIn, eBay, NASA and Medium have adopted Node.js, and most professional developers will have encountered Node.js tools.

    Below, we’ll look at some of the reasons you should consider using Node.js.

    It’s JavaScript

    JavaScript is used on trillions of web pages, where it has a browser monopoly. Every professional web developer requires JavaScript knowledge to program client-side applications.

    Server-side languages are more diverse. Historically, developers could opt for PHP, Ruby, Python, C# (ASP.NET), Perl, or Java, but these have different syntaxes and concepts. It can be difficult to switch contexts, so larger project teams often split into frontend and backend developers.

    Node.js allows a developer with frontend JavaScript knowledge to leverage their skills on the backend. It won’t make you a full-stack developer overnight, but the concepts are similar, and there’s less rigmarole when formatting JSON, handling character sets, using WebSockets, and so on.

    JavaScript Alternatives

    Some developers prefer languages such as TypeScript, PureScript, CoffeeScript, Reason, and Dart, which can transpile to JavaScript and run in a browser or Node.js. Ultimately, it still results in JavaScript code.

    It’s Fast

    Most server-side languages are fast enough, but few match the speed of Node.js. The V8 engine is quick, and it evolves rapidly, having the weight of Google and Chrome behind its development. Node.js also has a non-blocking, event-driven I/O.

    Let’s go through that again with less jargon. Most languages use synchronous blocking execution. When you issue a command—such as fetching information from a database—that command will halt further processing and complete before the runtime progresses to the next statement. To ensure that multiple users can have access at the same time, web servers such as Apache create a new processing thread for every request. This is an expensive operation, and Apache has a default limit of 150 concurrent connections. Busy servers can become overloaded.

    Node.js code (and browser JavaScript) runs on a single processing thread. Long-running tasks such as a database query are processed asynchronously, which doesn’t halt execution. The task runs in the background, and Node.js continues to the next command. When the task is complete, the returned data is passed to a callback function. A Node.js program can have many hundreds of ongoing operations that are completed whenever they’re finished, meaning that the processor is free to tackle other tasks.

    Asynchronous programming has challenges, but it’s possible to create fast Node.js applications that scale well.

    It’s Real-time

    Web platform features such as WebSockets and server-sent events permit real-time functionality—such as instant data updates, live chat, multiplayer games, and more. These can be difficult to implement in traditional server-side languages, where they often require third-party services. Real-time functionality in Node.js is significantly easier.

    It’s Lightweight

    The Node.js runtime is small and cross-platform. As well as catering for Linux, macOS, and Windows, you find editions for embedded systems, the Raspberry Pi, and even SpaceX rockets.

    It’s Modular

    Node offers a minimal standard library with good documentation. It contains basic functions for error handling, file system access, network operations, and logging.

    For everything else …

    It’s Extendible

    Node.js has the largest package registry in the world, with more than one million modules. You’ll find pre-written code for task runners, loggers, database connectors, image processors, code compilers, web servers, API managers, and even client-side libraries.

    The npm command-line tool is provided with Node.js and makes it easy to install, update, and remove modules. You can also use it to install global modules so Node.js scripts can run as commands from anywhere on your system.

    It’s Open Source

    Node.js is an open-source project. The runtime is free to use without any commercial restrictions. The majority of modules are also free, because they’re submitted by the community for the benefit of other developers.

    It’s Everywhere

    This course concentrates on web applications, but you can use Node.js to create serverless functions, deployment scripts, cross-platform command-line tools, and even complex graphical apps such as VS Code, Slack, and Skype—all of which use the Electron framework.

    As a web developer, you’ll almost certainly encounter Node.js, even if it’s not a core part of your technology stack. Knowing a little Node.js could help your projects and career. You’ll have a better insight into the possibilities available to modern web applications.

    What About Deno?

    Node.js is a cross-platform, V8-based JavaScript runtime released by Ryan Dahl in 2009.

    Deno is a cross-platform, V8-based JavaScript runtime released by Ryan Dahl in 2020.

    Deno smooths over some cracks and inconsistencies of Node.js, with the benefit of a decade’s worth of hindsight. It directly supports TypeScript without a compiler, uses ES6 modules rather than CommonJS, replicates many browser APIs (window, addEventListener, Fetch, Web Workers, etc.), and provides built-in tools for linting, testing, and bundling.

    Deno is great—but it’s new, and yet to achieve a fraction of Node’s popularity. The frameworks are similar: if you know one, it’s easy to switch to the other.

    Summary

    In this chapter, you’ve learned that Node.js is a popular JavaScript runtime that’s uniquely suited to web development. I’ve summarized it in this chapter’s video. Chapter 2 describes how to install Node.js on your platform of choice.

    Quiz

    Many chapters in this course end with a quick quiz to ensure you’ve grasped the concepts. Beware! Some questions are designed to catch you out, so make sure you’ve been paying attention! Answers can be found in Appendix A, at the back of the book.

    1. What is Node.js?

    a. A JavaScript runtime.

    b. A tool for creating command-line, GUI, and web applications.

    c. A cross-platform programming framework.

    d. All of the above.

    2. What is JavaScript’s relationship to Java?

    a. JavaScript is a cut-down version of Java.

    b. JavaScript is a cross-platform version of Java.

    c. JavaScript is Java that runs in a web browser.

    d. JavaScript is a marketing name.

    3. What is not another name for JavaScript?

    a. ECMAScript

    b. TypeScript

    c. JScript

    d. ES2015

    4. What best describes the Node.js non-blocking, event-driven I/O?

    a. Code that runs in separate processing threads.

    b. Code that runs synchronously; the next command runs after the current command has completed.

    c. Code that runs asynchronously; the next command could run before the current command has completed.

    d. Code that runs in parallel with other processes.

    5. What is npm short for?

    a. Node Package Manager

    b. Node Program Maintenance

    c. Node Parsing Methods

    d. Node.js Perfect Manual

    Chapter 2: Install Node.js

    You won’t get far on your Node.js journey without installing the runtime first! You have three primary options:

    Install Node.js on your local development machine running Linux, macOS, or Windows.

    This is the easiest choice, and the best way to get started—and it’s the option we’ll be taking here.

    Install Node.js via a virtual machine (typically Linux) running on Hypervisor software such as VMware, VirtualBox, Parallels, or Hyper-V.

    This won’t affect your main OS, so you can experiment without risk.

    Windows users should also consider the Windows Subsystem for Linux 2 (WSL2), which offers a highly integrated Linux environment. Follow the Linux instructions accordingly (found below in the How to Install Node.js on Linux (or Windows WSL2) section).

    Containerization software such as Docker.

    Docker provides a wrapper around applications known as a container. You’ll use Docker in later chapters to install software such as databases, but you can also develop, debug, and deploy Node.js apps in a similar way.

    A configured container runs identically on every OS, so it’s ideal when working in teams where members have different devices.

    Node.js apps will work cross-platform, but there are differences in file systems and supported software. Web applications are typically deployed to a Linux server, so developing on a Linux OS, virtual machine, or Docker container can help to avoid compatibility issues.

    Node Version Manager

    Node Version Manager (nvm) is a tool that allows multiple editions of Node.js to be installed on the same Linux, macOS, or Windows WSL system. This can be practical if you’re working on two or more projects using different versions of Node.js.

    Choosing a Node.js Version

    Install a recent release of Node.js unless you’re supporting a legacy application with specific requirements.

    Even-numbered Node.js versions—such as 16, 18, and 20—focus on stability and security with long-term support (LTS). Updates are provided for at least two years, so I recommend them for live production servers. You should install an identical version on your development machine.

    Odd-numbered versions—such as 15, 17, 19—are under active development and may have experimental features. They’re fine for development if you’re learning, experimenting, or upgrading frequently.

    Node.js 16 was used to develop the example code in this course. However, Node.js generally has good backward compatibility, and applications written in earlier editions of the framework usually run in later versions.

    How to Install Node.js on Linux (or Windows WSL2)

    Open the nodejs.org home page in your browser and you’ll be directed to download an installation package appropriate for your OS. However, it’s most practical to use the package manager built into your OS. Ubuntu and Debian binaries are available from NodeSource and, using version 16.x as an example, you can install Node.js from an Ubuntu bash terminal like so:

    curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -

    sudo apt-get install -y nodejs

    Verify that Node.js and npm are installed correctly by running the following commands in the terminal to view their version numbers:

    node -v

    npm -v

    Node and npm versions

    Configuring npm Global Permissions on Linux

    The Node Package Manager command-line tool is provided with Node.js and makes it easy to install, update, and remove modules. Where practical, Node.js apps can be installed globally and run from anywhere—such as the Rollup bundler for optimizing client-side JavaScript:

    npm install rollup --global

    This command results in a EACCES permission error, because you’re not running as a superuser or using sudo. However, sudo grants unlimited permissions to global scripts. I’d rather not run my own code that way, let alone someone else’s!

    A better option is to change the default npm directory to one owned by you. Create a new directory for global modules, then configure npm, like so:

    mkdir

    Enjoying the preview?
    Page 1 of 1