14455512
14455512
com
DOWLOAD EBOOK
https://ebooknice.com/product/advanced-node-js-development-35497072
ebooknice.com
https://ebooknice.com/product/node-js-web-development-6794442
ebooknice.com
https://ebooknice.com/product/web-development-with-mongodb-and-node-
js-55923446
ebooknice.com
https://ebooknice.com/product/node-js-web-development-11655364
ebooknice.com
ebooknice.com
https://ebooknice.com/product/node-js-for-php-developers-porting-php-
to-node-js-4078222
ebooknice.com
ebooknice.com
Learning Node.js Development
-FBSOUIFGVOEBNFOUBMTPG/PEFKTBOEEFQMPZBOEUFTU
/PEFKTBQQMJDBUJPOTPOUIFXFC
Andrew Mead
BIRMINGHAM - MUMBAI
Learning Node.js Development
Copyright a 2018 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 or its dealers and distributors, will be held liable for any damages caused or alleged to
have been 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.
ISBN 978-1-78839-554-0
XXXQBDLUQVCDPN
NBQUJP
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as
well as industry leading tools to help you plan your personal development and advance
your career. For more information, please visit our website.
Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos
from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
PacktPub.com
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 XXX1BDLU1VCDPN and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at TFSWJDF!QBDLUQVCDPN for more details.
At XXX1BDLU1VCDPN, 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.
Contributor
Andrew currently teaches Node, Gulp, and React. Before he started teaching, he created a
web app development company. He has helped companies of all sizes launch production
web applications to their customers. He has had the honor of working with awesome
companies such as Siemens, Mixergy, and Parkloco. He has a Computer Science degree
from Temple University, and he has been programming for just over a decade. He loves
creating, programming, launching, learning, teaching, and biking.
Packt is searching for authors like you
If you're interested in becoming an author for Packt, please visit BVUIPSTQBDLUQVCDPN and
apply today. We have worked with thousands of developers and tech professionals, just
like you, to help them share their insight with the global tech community. You can make a
general application, apply for a specific hot topic that we are recruiting an author for, or
submit your own idea.
Table of Contents
Preface 1
Chapter 1: Getting Set Up 7
Node.js installation 7
Node.js version confirmation 9
Installing Node 11
Verifying installation 12
What is Node? 15
Differences between JavaScript coding using Node and in the browser 22
Why use Node 32
Blocking and non-blocking software development 34
The working of blocking I/O 36
The working non-blocking I/O 39
Blocking and non-blocking examples using Terminal 45
Node community – problem solving open source libraries 50
Different text editors for node applications 54
Hello World – creating and running the first Node app 55
Creating the Node application 55
Running the Node application 58
Summary 62
Chapter 2: Node Fundamentals – Part 1 63
Module basics 64
Using case for require() 65
Initialization of an application 65
The built-in module to use require() 68
Creating and appending files in the File System module 69
The OS module in require() 75
Concatenating user.username 80
Using template strings 81
Require own files 83
Making a new file to load other files 84
Exporting files from note.js to use in app.js 87
A simple example of the working of the exports object 88
Exporting the functions 90
Exercise – adding a new function to the export object 93
Solution to the exercise 94
Third-party modules 97
Table of Contents
[ ii ]
Table of Contents
[ iii ]
Table of Contents
[ iv ]
Visit https://ebooknice.com to
discover a wide range of
eBooks across various genres.
Enjoy exclusive deals and
discounts to enhance your
reading experience. Start your
digital reading journey today!
Table of Contents
[v]
Table of Contents
[ vi ]
Table of Contents
[ vii ]
Table of Contents
[ viii ]
Table of Contents
[ ix ]
Preface
Welcome to Learning Node.js Development. This book is packed with a ton of content,
projects, challenges and real-world examples, all designed to teach you Node by doing. This
means you'll be getting your hands dirty early on in the upcoming chapters writing some
code, and you'll be writing code for every project. You will be writing every line of code
that powers our applications. Now, we would require a text editor for this book. We have
various text editor options that you can use. I always recommend using Atom, which you
can find at BUPNJP. It's free, open-source, and it's available for all operating systems,
namely Linux, macOS, and Windows. It's created by the folks behind GitHub.
All the projects in the book are fun to build and they were designed to teach you everything
required to launch your own Node app, from planning to development and testing to
deploying. Now, as you launch these different Node applications and move through the
book, you will run into errors, which is bound to happen. Maybe something doesn't get
installed as expected, or maybe you try to run an app and instead of getting the expected
output, you get a really long obscure error message. Don't worry, I am there to help. I'll
show you tips and tricks to get pass through those errors in the chapters. Let's go ahead and
get to it.
$IBQUFS, Node Fundamentals - Part 1, talks about building Node applications. The Node
Fundamentals topic has been divided into 3 parts. Part 1 of this topic includes module basics,
requiring own files, and third-party NPM modules.
Preface
$IBQUFS, Node Fundamentals - Part 2, continues our discussion on some more Node
fundamentals. This chapter explores yargs, JSON, the addNote function, and refactor,
moving functionality into individual functions and testing the functionality.
$IBQUFS, Node Fundamentals - Part 3, includes things such as read and write from the file
system. We'll look into advanced yargs configuration, debugging broken apps, and some
new ES6 functions.
$IBQUFS, Basics of Asynchronous Programming in Node.js, covers basic concepts, terms, and
technologies related to the async programming, making it super-practical and using it in
our weather application.
$IBQUFS, Promises in Asynchronous Programming, is the third and last part of async
programming in Node. This chapter focuses on Promises, how it works, why they are
useful, and so on. At the end of this chapter, we'll use Promises in our weather app.
$IBQUFS, Web Servers in Node, talks about Node web servers and integrating version
control into Node applications. We'll also introduce a framework called Express, one of the
most important NPM libraries.
$IBQUFS, Deploying Applications to Web, talks about deploying the applications to the Web.
We'll be using Git, GitHub, and deploy our live app to the Web using these two services.
$IBQUFS, Testing the Node Applications- Part 1, talks about how we can test our code to
make sure it is working as expected. We'll work on setting up for testing and then writing
our test cases. We'll look into the basic testing framework and asynchronous testing.
$IBQUFS, Testing the Node Application - Part 2, continues our journey of testing Node
applications. In this chapter, we'll work on testing the Express applications and look into
some advanced methods of testing.
[2]
Preface
lodash
nodemon
yargs
request
axios
express
hbs
heroku
rewire
Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:
[3]
Preface
Conventions used
There are a number of text conventions used throughout this book.
$PEF*O5FYU: 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: "Mount the downloaded 8FC4UPSN ENH disk image file as another disk in
your system."
DPOTUGTSFRVJSF GT
DPOTU@SFRVJSF MPEBTI
DPOTUZBSHTSFRVJSF ZBSHT
When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
DPOTUBSHWZBSHTBSHW
WBSDPNNBOEQSPDFTTBSHW<>
DPOTPMFMPH $PNNBOE DPNNBOE
console.log('Process', process.argv);
DPOTPMFMPH :BSHT BSHW
[4]
Preface
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:
"Select System info from the Administration panel."
Get in touch
Feedback from our readers is always welcome.
General feedback: Email GFFECBDL!QBDLUQVCDPN 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 RVFTUJPOT!QBDLUQVCDPN.
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 XXXQBDLUQVCDPNTVCNJUFSSBUB, 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 DPQZSJHIU!QBDLUQVCDPN 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
BVUIPSTQBDLUQVCDPN.
[5]
Visit https://ebooknice.com to
discover a wide range of
eBooks across various genres.
Enjoy exclusive deals and
discounts to enhance your
reading experience. Start your
digital reading journey today!
Preface
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!
[6]
Getting Set Up
1
In this chapter, you'll get your local environment set up for the rest of the book. Whether
you're on macOS, Linux, or Windows, we'll install Node and look at exactly how we can
run Node applications.
We'll talk about what Node is, why you would ever want to use it, and why you would
want to use Node as opposed to something like Rails, C++, Java, or any other language that
can accomplish similar tasks. By the end of this chapter, you will be running your very first
Node application. It's going to be simple, but it is going to get us to the path to creating real-
world production Node apps, which is the goal of this book.
Node.js installation
What Node is
Why use Node
Atom
Hello World
Node.js installation
Before we start talking about what Node is and why it's useful, you need to first install
Node on your machine, because in the next couple of sections, we'll want to run a little bit
of Node code.
Now, to get started, we just need two programsba browser, I'll be using Chrome
throughout the book, but any browser will do, and Terminal. I'll use Spotlight to open up
Terminal, which is what it's known as on my operating system.
Getting Set Up Chapter 1
If you're on Windows, look for the Command Prompt, you can search using the Windows
key and then by typing DPNNBOEQSPNQU, and on Linux, you're looking for the command
line, although depending on your distribution it might be called Terminal or Command
Prompt.
Now, once you have that program open, you'll see a screen, as shown in the following
screenshot:
Essentially, it's waiting for you to run a command. We'll run quite a few commands from
Terminal throughout the book. I'll discuss it in a few sections later, so if you've never used
this before, you can start navigating comfortably.
[8]
Getting Set Up Chapter 1
[9]
Getting Set Up Chapter 1
ES6 is the next version of JavaScript and it comes with a lot of great enhancements we'll be
using throughout the book. If you look at the following image, Node.js Long Term Support
Release Schedule (IUUQTHJUIVCDPNOPEFKT-54), you can see that the current Node
version is V8, out in April 2017:
Before going further, I would like to talk about the Node release cycle. What I have in the
preceding image is the official release cycle, this is released by Node. You'll notice that only
next to the even Node numbers do you find the active LTS, the blue bar, and the
maintenance bar. Now, LTS stands for long-term support, and this is the version that's
recommended for most users. I'd recommend that you stick with the currently offered LTS
option (Node v 8.9.4 LTS), though anything on the left-hand side will do, this is shown as
the two green buttons on OPEFKTPSH.
Now, as you can see, the major version numbers, bump every six months. Regardless of any
sort of big overarching change, this happens like clockwork even if nothing drastic has
changed. It's not like Angular where jumping from 1.0 to 2.0 was almost like using a
completely different library. This is just not the case with Node, what you're getting from
this book is the latest and greatest Node has to offer.
[ 10 ]
Getting Set Up Chapter 1
Installing Node
Once the version is confirmed and selected, all we have to do is to click the required version
button on the Node website (OPEFKTPSH) and download the installer. The installer is one of
those basic click Next a few times and you're done type of installers, there's no need to run any
fancy commands. I'll start the installer. As shown in the following screenshot, it'll just ask a
few questions, then let's click on Next or Continue through all of them:
You might want to specify a custom destination, but if you don't know what that means,
and you don't usually do it when installing programs, skip that step too. Here, in the next
screenshot, you can see that I'm using just 58.6 MB, no problem.
[ 11 ]
Getting Set Up Chapter 1
I'll run the installer by entering my password. And once I enter my password, it should
really only take a couple of seconds to get Node installed:
As shown in the following screenshot, we have a message that says The installation was
completed successfully, which means we are good to go:
[ 12 ]
Getting Set Up Chapter 1
Verifying installation
Now that Node has been installed successfully, we can go ahead and verify that by running
Node from Terminal. Inside Terminal, I'll shut it down by going to Quit Terminal and open
it up again:
In our case, we restarted things and we can run our brand new command so, we'll type it:
node -v
[ 13 ]
Getting Set Up Chapter 1
What we're doing in this command is we're running the Node command, and we're passing
in what's called a flag, a hyphen sign followed by a letter. It could be B, it could be K, or in
our case it's W. This command will print the version of Node currently installed.
If you try to run a command that doesn't exist, such as OPEFBTEG, you'll see command not
found. If you see this, it usually means the Node installer didn't work correctly, or you
haven't run it in the first place.
In our case though, running Node with the W flag should result in a number. In our case, it's
version 9.3.0. If you do have Node installed, and you see something like the following
screenshot, then you are done. In the next section, we'll start exploring exactly what Node
is.
[ 14 ]
Exploring the Variety of Random
Documents with Different Content
climax of the power of, 518;
suspension of, 520;
admission of the Commons to, 370
Parliaments,
annual, 496;
statutes relating to, 477
Popes, origin of the right of, to make and unmake kings, 96;
powers of the, 311, 317, 321;
resistance of the Commons to the, 490
Power, regal,
extension of, 148, 151;
causes of the, 160, 276;
theory of, 218, 446;
origin of, 219;
struggles of, with feudal powers, 308-325;
restrictions to, 361;
resistance of the Commons to, 477
Problem of government, 78
Publicity,
an essential characteristic of representative government, 80, 265
Publicity, in England, 81
R.
Representation,
political meaning of the term, 334, 348;
theories of, 335, 336, 341;
doctrine of, 347;
first development of, in English government, 354, 355;
progress of, 363, 367
Representatives of counties,
election of, 381;
payment of, 383, 461;
number of, 405;
coalition of, with members for boroughs, 422;
qualifications of, 410
Revolutions,
general effects of, on society, 2, 10;
epochs of, 187
Richard II.,
reign of, 494-506;
government of, 500;
deposition of, 505, 506, 509;
political character of, 507, 508
Right,
impossibility of defining, 429;
philosophy of, 426, 437, 430;
legitimacy of, 431
Right,
initiative, 464, 471;
completion of the, 514
Rights, national, 63
Rome,
political institutions of, 184;
classification of the inhabitants of, 193, 200;
centralization of power in, 202
Rousseau,
his hypothesis of society, 57;
his theory of representation, 335, 337, 339
Royalty, theory of, 218;
struggles with feudal aristocracy, 311, 317, 322, 327
Royalty,
Anglo-Norman, 295;
wealth and power of, 296-299
S.
Savigny, M. de,
on the laws of the Visigoths, 241, 244
Saxons,
enmity of, to the Danes, 270;
analogy of, with the Normans, 282;
national assemblies of the, 291-293
School, philosophic,
fundamental principles of, 426;
errors of the, 427, 429, 430, 432
School,
historic principles of the, 426;
errors of the, 433
Science, political, 389
Scribæ, 199
Scotland,
early independence of, 484;
wars of, 486
Service, military,
origin of, 109;
limits of, 110;
exaction of, 326
Society,
classification of, 33;
origin of, 57;
philosophy of, 57;
desire and tendency of, 66, 438, 439;
earliest condition of, 133;
tests of the social condition of, 137;
meaning and object of, 441;
government of, 288;
parliamentary classification of, 420, 422;
great aim of, 432, 438
Society, Christian,
influence of, on the fallen powers of Rome, 187;
growth of, 189
Sovereignty,
right of, 58;
effects of, 67;
theories of, 263, 264;
opinions of Bracton and Fortescue on, 267
Sovereignty, individual,
theory of, 336-338, 242;
results of, 443;
division of, 445
Spain,
under the Roman Empire, 206;
invasion of, 209;
monarchy in, 210;
fall of the, 214;
division of, into dioceses, 213;
Gothic laws of, 246, 247;
institutions of, 235
State,
councils of, 165;
revenues of the, 487
States,
modern, 201, 448;
comparison of, with the Roman Empire, 113, 201
Stephen,
wars of, 274;
regal power of, 300;
charters of, 305
Subsidies,
conditions attached to, 461, 497, 498;
appropriation of, 480
Succession, hereditary, 101, 158, 159, 209, 212
Susceptor, 199
System, feudal, 14, 35, 126, 173, 146, 158, 171, 175;
establishment of, in Normandy, 103, 283;
origin of the, 112
System, representative,
nature of the, 348;
object of, 440;
principle of, 440, 449
T.
Tabularii, 147
Talliage, 364
Theodoric,
dominions of, 86
invasion of Spain by, 207;
death of, 208
Thorismund, 208
Time,
past, importance of the study of, 5;
present characteristics of the, 21
Tories,
their estimation of Saxon and Norman institutions, 283;
opinions of, on national assemblies, 290;
on electors, 377;
theories of, refuted, 382
Towns, English,
importance of, 268, 306, 362, 364;
liberties of, 265, 280;
effects of the Norman conquest on, 294;
deputies of, called to Parliament, 362;
representation of, 366
Truth,
difficulty of attaining the, 19;
characteristics of, 68
Tyranny,
local, effects of, 174;
origin of; 340, 341
Tythes,
institution of, 326;
continuation of, 372
U.
Unity,
definition of, 62, 265;
power of, in government, 72
V.
Vassals,
etymology of the term, 122;
condition of, 175
Visigoths,
laws of the, 119, 125, 177, 208, 215;
national assemblies of, 211;
institutions of, 237
Visigoths, monarchy of the, in Gaul, 207, 208
Visigoths,
bishops of the, 232;
character of, 236
Visigoths,
kings of the, 207-214;
duties of the, 225
W.
Wamba, 213
Wars of Clovis, 34
Wittenagemot,
composition of the, 46;
powers of, 49, 51;
character of the, 52;
assemblies of the, 284, 292, 449
Withema, 211
Y.
[Transcriber's note: The prices listed use the £sd system (or Lsd),
"pounds, shillings and pence," from librae, solidi, and denarii.
12d (pence) is a shilling. 20s (shillings), or 240d (pence), is a
pound. The purchasing power of one pence is 1852 is about
US$.58 in 2020. A common price of 3s. 6d. is about $40.]
Publisher's Advertisements
Bohn's Classical Library,
1. Herodotus.
By The Rev. Henry Cary, M.A. Frontispiece.
2 & 3. Thucydides.
By The Rev. H. Dale.
In 2 Vols. (3s. 6d. Each). Frontispiece.
38. Demosthenes.
The Olynthiac, Philippic, and other Public Orations, with Notes,
Appendices, &c., by C. Rann Kennedy. (3s. 6d.)
54. Plato. Vol VI., completing the work, and containing Epinomis,
Axiochus, Eryxias, on Virtue, on Justice, Sisyphus, Demodocus, and
Definitions; the Treatise of Timæus Locrus on the Soul of the World
and Nature; the Lives of Plato by Diogenes Laertius, Hesychius, and
Olympiodorus; and the Introductions to his Doctrines by Alcinous
and Albinus; Apuleius on the Doctrines of Plato, and Remarks on
Plato's Writings by the Poet Gray. Edited, with Notes, by G. Burges,
M.A., Trin. Coll., Camb. With general Index to the 6 Volumes.
64. 67, 69, 72, 78, & 81. Pliny's Natural History, with copious
Notes, by Dr. Bostock and T. H. Riley. In 6 volumes. Vols. I., II.,
III., IV., V. and VI.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com