Professional Documents
Culture Documents
Learning Node Js Development Learn The Fundamentals of Node Js and Deploy and Test Node Js Applications On The Web 1st Edition Andrew Mead
Learning Node Js Development Learn The Fundamentals of Node Js and Deploy and Test Node Js Applications On The Web 1st Edition Andrew Mead
https://textbookfull.com/product/pro-express-js-master-express-
js-the-node-js-framework-for-your-web-development-mardan-azat/
https://textbookfull.com/product/full-stack-javascript-learn-
backbone-js-node-js-and-mongodb-mardan-azat/
https://textbookfull.com/product/fullstack-node-js-the-complete-
guide-to-building-production-apps-with-node-js-davit-guttman/
Node js web development server side development with
Node 10 made easy Fourth Edition. Edition David Herron
https://textbookfull.com/product/node-js-web-development-server-
side-development-with-node-10-made-easy-fourth-edition-edition-
david-herron/
https://textbookfull.com/product/jump-start-node-js-get-up-to-
speed-with-node-js-in-a-weekend-1st-edition-nguyen-don/
https://textbookfull.com/product/instant-node-js-starter-1st-
edition-teixeira-pedro/
https://textbookfull.com/product/secure-your-node-js-web-
application-keep-attackers-out-and-users-happy-1st-edition-karl-
duuna/
https://textbookfull.com/product/professional-node-js-building-
javascript-based-scalable-software-1st-edition-teixeira-pedro/
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 ]
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]
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 ]
Another random document with
no related content on Scribd:
— Écoutez-moi. Je vous aime. Souvenez-vous. J’ai eu tort de
vous quitter ainsi. J’étais fou… L’assassinat, la guerre, j’étais fou…
Pardonnez-moi. J’ai trop souffert… Si vous saviez !
— Et moi, croyez-vous que je n’aie pas souffert ? Elle parlait
durement, avec un accent découpé. « Ah ! vous souffriez ? Et moi, et
moi… Vous êtes parti sans un mot, sans un regard, lâchant votre
fiancée comme une gueuse… Vous ne m’avez pas même écrit. Vous
m’avez préféré je ne sais quelles idées, je ne sais quel orgueil.
Quand ma chair était happée par la guerre, vous vous êtes écarté de
l’engrenage. Vous avez préféré la paix à mon amour ! » Cette fois,
elle avait les yeux dans ses yeux. Au bout des mains serrées, ses
doigts s’étaient joints. Du talon, elle martelait les planches : « Que
faites-vous ici, quand ceux de votre âge meurent, quand Georges,
en ce moment, peut-être, tombe dans sa tranchée, quand on fusille
Richard ou qu’il s’écrase sur le sol, quand vos amis sont entre la
tempête et vous. Cela pour vous protéger. Cela pour vous, qui êtes
ici. Cela pour vos semblables, les neutres, qui se voilent les yeux
d’une main et détroussent les cadavres de l’autre. Vous, vous ! »
Elle tremblait de colère. De nouveau, elle fut très belle. Mais
comme il se sentait aimé, comme il la tenait sous sa griffe, comme
ce n’était plus ce silence épouvantable du matin, l’incertitude,
l’absence, la perspective encore de longs mois, d’années sans la
voir, sans entendre parler d’elle, il se tassa dans sa demi-victoire, il
fit front. Il ne voulut pas qu’elle pensât hors de lui-même. Il songea
au miracle de la veille, quand elle roulait dans son sillage, éperdue
de reconnaissance à ne dépendre que de lui.
— Je fais ce que je peux pour arracher mes amis au massacre,
pour arrêter le massacre. Georges vient de m’écrire. Il désespère. Il
est écœuré. Et tous ainsi, partout. Vous n’êtes donc pas encore
saoulée de sang ?
Elle blêmit, mais sentit la houle guerrière monter de ses entrailles
et soulever son cœur.
— Vous savez que s’il faut le mien pour que le massacre cesse, il
cessera à l’instant. Mais à condition que le bourreau, après, jette sa
hache, rentre dans sa patrie, cultive son jardin. Je lui pardonne par
amour pour ceux de la Marne, qui lui ont cassé les genoux.
— Le bourreau, mais c’est l’internationale toute entière du
capital ! Ceux de la Marne ? Des esclaves. Avez-vous jamais réfléchi
à la somme de lâcheté qu’il faut pour se laisser jeter à la tuerie
contre son gré ? La patrie ? les patries ? elles ne commenceront à
vivre que le jour où mourra la guerre.
— Si nous ne tuons pas la guerre, vous savez bien que ce sera
le triomphe de la patrie qui croit le plus à la patrie et aura déchaîné
la guerre. Par haine du chauvin d’ici, vous en êtes un de là-bas.
— Mais eux vivent, du moins. C’est le peuple le plus vivant. Il est
organisé. Il est cohérent. Il va d’un bloc ; et nous ne sommes que
poussière.
Elle eut un rire ardent.
— La poussière a brisé le bloc. Et pour vous le bloc est force et la
poussière lâcheté. Riez donc avec moi, Monsieur le logicien. C’est
vous qui profitez du sacrifice, visitez les musées, ascensionnez,
philosophez, palabrez, c’est vous le lâche !
— Hélas ! vous savez bien que je ne profiterai pas de ce que
vous appelez le sacrifice. Vous savez bien que ma vie est perdue.
Vous savez bien que la France m’est interdite. Je suis un réprouvé.
— Alors, pourquoi as-tu fait ça ?
Il chancela.
— Ma conscience me défend de tuer.
— Niaiserie. A la guerre, on ne tue pas. On délivre. Ah ! vous
êtes un réprouvé ! Auriez-vous donc une patrie, comme les autres ?
Votre conscience est bonne fille. Elle laisse mourir les « lâches »
pour défendre le sol, les eaux, les mots, les images qui l’ont faite. Et
vous le savez bien, et vous le savez bien ! Vous profitiez plus qu’eux
de la patrie. Ils en bêchaient la terre, vous en mangiez le pain. Vous
en respiriez les fleurs, l’âme.
— C’est cette âme qui m’a appris l’amour de l’âme universelle
qu’expriment toutes les patries dans un langage différent.
— Soit. Mais si l’une de ces patries veut broyer l’âme de la
vôtre ?
Il ne répondit pas. Ils avaient quitté le petit pont. D’instinct, à
travers les rues de la ville, ils se dirigeaient vers l’hôtel. Pierre
regardait distraitement les devantures cossues, hymnes plastiques
au tourisme et à la santé, où les vingt ours taillés dans le mélèze
pour orner les encriers, les parapluies, les couteaux, les étagères,
les pendules, exprimaient des besoins esthétiques à coup sûr
beaucoup plus honnêtes que ceux dont la carte postale obscène
témoigne aux louches étalages des métropoles enragées de la
luxure et du combat. Une détresse immense environnait son amour.
Toujours hostile, mais inquiète de son silence, celle qui marchait
près de lui attendait. Il allait dire : « Je vous aime » quand, au
tournant de la dernière rue avant d’arriver à l’hôtel, ils se heurtèrent
à Clotilde qui venait au-devant d’eux, un télégramme à la main :
— Où est papa ? Georges…
— Georges, mon Georges !
Élisabeth avait saisi le papier : Georges blessé grièvement.
Venez.
Pierre serra les poings : « Hélas ! vous voyez bien.
— Quoi ?
— Lui aussi, lui aussi ! Pauvre petit ! Et vous ne voulez pas que
ça finisse ?
— Je vois qu’il paie vingt siècles d’une grandeur à qui il doit toute
la sienne, et que vous avez fait faillite, vous.
— Mais vous savez bien qu’il trouve le prix excessif ! Il n’a rien à
payer. Vous l’immolez à une idole. Et il commence à le savoir…
— Il est jeune. Il souffre. Il le dit. Je lui pardonne et je l’adore.
Vous, je vous hais.
Il lui saisit le poing :
— Pourquoi m’avez-vous dit tu tout à l’heure ?
— Parce que je vous aime.
Il eut un élan victorieux, la tira à lui violemment.
— Alors ?
Elle se dégageait, folle de rage et d’amour.
— Alors, rentrez en France, battez-vous.
— Non.
— Vous êtes une femme. Non, une fille. Adieu !
V