W Java142
W Java142
JS
Node.js
TABLE OF CONTENTS
Preface 1
Introduction 1
Advantages and Disadvantages of Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Installing Node.js 1
Node.js Architecture 2
Node.js Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
The Event Loop 3
Common APIs 4
The Node Package Manager (NPM) 6
Node.js "Hello Word" Example 7
Pyramid Of Doom 8
Popular Modules And Frameworks 10
Resources 11
PREFACE
PREFACE Advantages Disadvantages
Follow the on-screen instructions in the installer to • V8 Engine: At the core of Node.js is the V8
install Node.js on your system. You can typically JavaScript engine, developed by Google. V8 is
accept the default settings, but you may customize known for its high-performance JavaScript
the installation directory if needed. execution and just-in-time (JIT) compilation of
JavaScript code into native machine code. This
6. Verify the installation enables Node.js to execute JavaScript with
remarkable speed.
After the installation is complete, open a terminal
• Libuv: Libuv is a C library that Node.js uses to
or command prompt, and type the following
abstract and handle I/O operations and provide
commands to verify that Node.js and NPM (Node
an event loop. It enables Node.js to work across
Package Manager) are correctly installed:
various operating systems, managing tasks like
file system operations and network
node -v communication in an efficient, non-blocking
manner.
npm -v
• Event Loop: The event loop is the central part
of Node.js, responsible for managing
These commands should display the versions of
asynchronous operations. It allows Node.js to
Node.js and NPM, confirming that the installation
handle I/O operations, such as file reading,
was successful.
network requests, and database queries,
without blocking the entire process. Node.js is
7. Optional: Install a code editor (IDE)
single-threaded, but the event loop’s non-
blocking I/O operations make it highly efficient
To start developing with Node.js, you may want to
for handling a large number of concurrent serves as a set of built-in libraries that extend the
connections. capabilities of JavaScript beyond what’s available in
a browser environment.
• Callback Queue: Callbacks are functions that
are executed once an asynchronous operation
Finally, the application layer is where Node.js
is completed. Node.js relies on a callback
developers write their JavaScript code to create
mechanism to handle asynchronous code.
server-side applications and services. This layer
When an asynchronous task finishes, its
includes the user’s custom JavaScript code, which
callback is placed in the callback queue, and
utilizes the Node.js API and any additional third-
the event loop processes these callbacks in a
party modules installed via NPM. Developers build
first-in, first-out (FIFO) order.
web servers, APIs, real-time applications, and
various other server-side applications in this layer.
NODE.JS STACK They also handle business logic and application-
specific functionality.
The Node.js stack consists of several layers, starting
with the V8 engine, linuv and other native support
THEEVENT
THE EVENTLOOP
LOOP
libraries at the core.
Under the hood, the npm install command By defining and running scripts in your
downloads the designated package from the package.json file, you can easily automate common
registry and installs it, along with all of its tasks, making it convenient to start, test, and
dependencies, to the node_modules/ directory inside manage your Node.js applications.
your project folder; it then updates your project’s
package.json file to include the newly added NODE.JS"HELLO
NODE.JS "HELLOWORD"
WORD"EXAMPLE
EXAMPLE
dependency. Open the package.json file, and you
should see an updated "dependencies" section that To run JavaScript files in Node.js, you can use the
lists the lodash package and its version. The latest node command followed by the name of the file
version available at the time of installation is containing the code to be executed.
selected.
For a "hello world" application, that simply outputs
a "hello world" message to the console, let’s create a
... JavaScript file, name it myapp.js (you are free to
"dependencies": { choose whatever name you like of course) and add
"lodash": "^4.17.21" the following code in it:
}
...
console.log("Hello, Node.js!");
"scripts": {
"test": "echo \"Error: no test // Import the 'http' module, which
specified\" && exit 1", is a built-in module for creating
"start": "node app.js" HTTP servers.
} const http = require('http');
...
// Define the hostname and port for
To run the script, use the npm run command the server to listen on.
followed by the script name like this: npm run start const hostname = '127.0.0.1'; //
Loopback address for the local
NPM also provides a few built-in scripts that you machine
can use without defining them in the "scripts"
const port = 3000; // Port number
section. Some common built-in scripts include:
Note that this application requires the http package Promises: Promise objects provide a way to handle
which allows us to create an HTTP server and asynchronous operations in a more linear and
handle incoming HTTP requests. You can install the readable fashion. They allow you to chain .then()
http package by running npm install http while in and .catch() calls, avoiding deeply nested
the top folder of your project. callbacks.
PYRAMIDOF
PYRAMID OFDOOM
DOOM
const fs = require('fs').promises;
The "pyramid of doom" is a term used to describe a // Using Promises for file
situation where multiple levels of nested callbacks operations
result in code that has a deeply nested and indented
structure. This nested structure can make your fs.readFile('file1.txt', 'utf8')
program hard to read, understand, and maintain, .then(data1 => fs.readFile(
resembling a pyramid-like shape. 'file2.txt', 'utf8'))
.then(data2 => fs.readFile(
The "pyramid of doom" typically occurs in scenarios
'file3.txt', 'utf8'))
like handling I/O operations, making network
requests, or dealing with event-driven
.then(data3 => {
programming in general. Here’s an example of the // Do something with data1,
"pyramid of doom" scenario using three nested data2, and data3
callbacks: })
.catch(err => {
use Node.js’s event emitter pattern to handle asynchronous code, making it more readable and
asynchronous events more elegantly. maintainable, while avoiding the pyramid of doom.
The choice of which approach to use depends on
the specific requirements of your project and your
const fs = require('fs'); personal coding style.
const EventEmitter = require('
events'); POPULARMODULES
POPULAR MODULESAND
AND
FRAMEWORKS
FRAMEWORKS
const emitter = new EventEmitter();
The Node.js ecosystem thrives on the contributions
emitter.on('data1', () => { of third-party developers, resulting in a vast
fs.readFile('file1.txt', 'utf8', collection of modules and frameworks that extend
(err, data1) => { the capabilities of Node.js for various purposes. In
if (err) { this table, we provide a quick overview of some of
the most popular third-party modules and
console.error(err);
frameworks, along with brief descriptions of their
} else {
key features and use cases. These tools empower
emitter.emit('data2', data1);
Node.js developers to streamline development,
} implement real-time features, simplify
}); authentication, and much more. Explore this table
}); to discover the wealth of resources available to
enhance your Node.js projects.
emitter.on('data2', (data1) => {
fs.readFile('file2.txt', 'utf8', Module/framework Description
(err, data2) => { Express Express.js is a widely
if (err) { used web application
console.error(err); framework for Node.js.
} else { It simplifies the process
emitter.emit('data3', data1, of building robust and
data2); scalable web
} applications with a rich
}); set of features and
middleware. Express is
});
known for its
minimalistic and
emitter.on('data3', (data1, data2)
flexible design.
=> {
fs.readFile('file3.txt', 'utf8', Passport Passport is an
authentication
(err, data3) => {
middleware for Node.js
if (err) {
applications. It supports
console.error(err);
various authentication
} else { strategies, such as
// Do something with data1, username and
data2, and data3 password, OAuth, and
} OpenID, making it easier
}); to implement user
}); authentication and
authorization in your
emitter.emit('data1'); web applications.
JCG delivers over 1 million pages each month to more than 700K software
developers, architects and decision makers. JCG offers something for everyone,
including news, tutorials, cheat sheets, research guides, feature articles, source code
and more.
CHEATSHEET FEEDBACK
WELCOME
[email protected]
Copyright © 2014 Exelixis Media P.C. All rights reserved. No part of this publication may be SPONSORSHIP
reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, OPPORTUNITIES
mechanical, photocopying, or otherwise, without prior written permission of the publisher. [email protected]