Node js By Example 1st Edition Tsonev 2024 Scribd Download
Node js By Example 1st Edition Tsonev 2024 Scribd Download
com
https://ebookname.com/product/node-js-by-example-1st-
edition-tsonev/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookname.com/product/node-js-blueprints-tsonev/
ebookname.com
https://ebookname.com/product/d3-js-by-example-1st-edition-heydt/
ebookname.com
https://ebookname.com/product/node-js-in-practice-1st-edition-alex-r-
young/
ebookname.com
https://ebookname.com/product/the-cambridge-handbook-of-policing-in-
the-united-states-1st-edition-tamara-rice-lave/
ebookname.com
Wealth Health and Democracy in East Asia and Latin America
1st Edition James W. Mcguire
https://ebookname.com/product/wealth-health-and-democracy-in-east-
asia-and-latin-america-1st-edition-james-w-mcguire/
ebookname.com
https://ebookname.com/product/adaptive-preferences-and-women-s-
empowerment-1st-edition-serene-j-khader/
ebookname.com
https://ebookname.com/product/commodity-trading-advisors-risk-
performance-analysis-and-selection-wiley-finance-1st-edition-greg-n-
gregoriou/
ebookname.com
https://ebookname.com/product/introduction-to-computational-linear-
algebra-1st-edition-erhel/
ebookname.com
https://ebookname.com/product/excursions-in-modern-mathematics-10th-
edition-peter-tannenbaum/
ebookname.com
The C Player s Guide 3rd Edition Rb Whitaker
https://ebookname.com/product/the-c-player-s-guide-3rd-edition-rb-
whitaker/
ebookname.com
www.it-ebooks.info
Node.js By Example
Krasimir Tsonev
BIRMINGHAM - MUMBAI
www.it-ebooks.info
Node.js By Example
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, and its dealers and distributors will be held liable for any damages
caused or alleged to be 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-78439-571-1
www.packtpub.com
www.it-ebooks.info
Credits
Reviewers Proofreaders
Danny Allen Stephen Copestake
Alex (Shurf) Frenkel Safis Editing
Technical Editor
Mrunal M. Chavan
Copy Editor
Vedangi Narvekar
www.it-ebooks.info
About the Author
www.it-ebooks.info
About the Reviewers
Alex (Shurf) Frenkel has worked in the field of web application development
since 1998 (the beginning of PHP 3.X) and has extensive experience in system
analysis and project management. Alex is a PHP 5.3 Zend Certified Engineer and is
considered to be one of the most prominent LAMP developers in Israel. He is also a
food blogger at http://www.foodstuff.guru.
In the past, Alex was the CTO of ReutNet, one of the leading Israeli web
technology-based companies. He also worked as the CEO/CTO of OpenIview
LTD—a company built around the innovative idea of breaching the IBM mainframe
business with PHP applications. He was also the CTO and the chief architect of
a start-up, GBooking. He also provided expert consulting services to different
companies in various aspects of web-related technology.
Foodstuff.Guru is a pet project that brings not only high-style food, but also every day
food to the Web that can be reviewed by people for people. The blog is multilingual
and you can visit it at http://www.foodstuff.guru.
www.it-ebooks.info
www.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 www.PacktPub.com
and as a print book customer, you are entitled to a discount on the eBook copy. Get in
touch with us at service@packtpub.com for more details.
At www.PacktPub.com, 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.
TM
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser
www.it-ebooks.info
Table of Contents
Preface v
Chapter 1: Node.js Fundamentals 1
Understanding the Node.js architecture 1
Installing Node.js 3
Running Node.js server 3
Defining and using modules 4
Managing and distributing packages 7
Creating a module 7
Using modules 8
Updating our module 9
Introducing built-in modules 10
Creating a server with the HTTP module 10
Reading and writing to files 11
Working with events 11
Managing child processes 13
Summary 14
Chapter 2: Architecting the Project 15
Introducing the basic layers of the application 15
The task runner and building system 18
Introducing Grunt 19
Discovering Gulp 22
Test-driven development 24
The Model-View-Controller pattern 27
Introducing the REST API concept 30
Summary 32
[i]
www.it-ebooks.info
Table of Contents
[ ii ]
www.it-ebooks.info
Table of Contents
[ iii ]
www.it-ebooks.info
Table of Contents
[ iv ]
www.it-ebooks.info
Preface
Node.js is one of the present day's most popular technologies. Its growing
community is known to produce a large number of modules every day. These
modules can be used as building blocks for server-side applications. The fact that
we use the same language (JavaScript) on both the server- and client-side make
development fluent.
This book contains 11 chapters that contain a step-by-step guide to building a social
network. Systems such as Facebook and Twitter are complex and challenging to
develop. It is nice that we will learn what Node.js is capable of, but it is going to
be much more interesting if we do that within a concrete context. The book covers
basic phases such as the architecture and management of the assets' pipeline, and it
discusses features such as users' friendship and real-time communication.
Chapter 2, Architecting the Project, reveals the power of build systems such as Gulp.
Before starting with our social network, we will plan the project. We will talk about
test-driven development and the Model-View-Controller pattern. The chapter will
cover the Node.js modules that are needed to bootstrap the project.
Chapter 3, Managing Assets, covers the building of a web application. So, we have to
deal with HTML, CSS, JavaScript, and images. In this chapter, we will go through the
processes behind the serving of assets.
[v]
www.it-ebooks.info
Preface
Chapter 6, Adding Friendship Capabilities, explains one of the main concepts behind
modern social networks—friendship. The ability to find friends and follow their
walls is an important part. This chapter is dedicated to the development of this
relationship between users.
Chapter 7, Posting Content, states that the backbone of every social network is the
content that users add into the system. In this chapter, we will implement the
process of post making.
Chapter 8, Creating Pages and Events, states that providing the ability to users to create
pages and events will make our social network more interesting. Users can add as
many pages as they want. Other users will be able to join the newly created places
in our network. We will also add code to collect statistics.
Chapter 9, Tagging, Sharing, and Liking, explains that besides posting and reviewing
content, the users of a social network should be able to tag, share, and like posts.
This chapter is dedicated to the development of these functions.
Chapter 10, Adding Real-time Chat, talks about the expectations of users, in today's
world, to see everything that is happening right away. They want to communicate
faster with each other. In this chapter, we will develop a real-time chat so that the
users can send messages instantly.
Chapter 11, Testing the User Interface, explains that it is important to get the job done,
but it is also important to cover working functionalities with tests. In this chapter,
we will see how to test a user interface.
[ vi ]
www.it-ebooks.info
Preface
Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "If
the Ractive component has a friends property, then we will render a list of users."
New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "It shows
their name and a Add as a friend button."
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for
us to develop titles that you really get the most out of.
[ vii ]
www.it-ebooks.info
Preface
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you would report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the errata submission form link,
and entering the details of your errata. Once your errata are verified, your submission
will be accepted and the errata will be uploaded on our website, or added to any list of
existing errata, under the Errata section of that title. Any existing errata can be viewed
by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.
We appreciate your help in protecting our authors, and our ability to bring you
valuable content.
[ viii ]
www.it-ebooks.info
Preface
Questions
You can contact us at questions@packtpub.com if you are having a problem with
any aspect of the book, and we will do our best to address it.
[ ix ]
www.it-ebooks.info
www.it-ebooks.info
Node.js Fundamentals
Node.js is one of the most popular JavaScript-driven technologies nowadays.
It was created in 2009 by Ryan Dahl and since then, the framework has evolved
into a well-developed ecosystem. Its package manager is full of useful modules
and developers around the world have started using Node.js in their production
environments. In this chapter, we will learn about the following:
Most of the servers written in Java or C use multithreading. They process every
request in a new thread. Ryan decided to try something different—a single-threaded
architecture. In other words, all the requests that come to the server are processed by
a single thread. This may sound like a nonscalable solution, but Node.js is definitely
scalable. We just have to run different Node.js processes and use a load balancer that
distributes the requests between them.
[1]
www.it-ebooks.info
Node.js Fundamentals
On top of these three blocks, we have several bindings that expose low-level
interfaces. The rest of Node.js is written in JavaScript. Almost all the APIs that we
see as built-in modules and which are present in the documentation, are written
in JavaScript.
[2]
www.it-ebooks.info
Chapter 1
Installing Node.js
A fast and easy way to install Node.js is by visiting https://nodejs.org/
download/ and downloading the appropriate installer for your operating system.
For OS X and Windows users, the installer provides a nice, easy-to-use interface.
For developers that use Linux as an operating system, Node.js is available in the APT
package manager. The following commands will set up Node.js and Node Package
Manager (NPM):
sudo apt-get update
sudo apt-get install nodejs
sudo apt-get install npm
If you run node ./server.js in your console, you will have the Node.js server
running. It listens for incoming requests at localhost (127.0.0.1) on port 9000. The
very first line of the preceding code requires the built-in http module. In Node.js,
we have the require global function that provides the mechanism to use external
modules. We will see how to define our own modules in a bit. After that, the scripts
continue with the createServer and listen methods on the http module. In this
case, the API of the module is designed in such a way that we can chain these two
methods like in jQuery.
[3]
www.it-ebooks.info
Node.js Fundamentals
The first one (createServer) accepts a function that is also known as a callback,
which is called every time a new request comes to the server. The second one makes
the server listen.
We encapsulate logic in modules. Every module is defined in its own file. Let's
illustrate how everything works with a simple example. Let's say that we have a
module that represents this book and we save it in a file called book.js:
// book.js
exports.name = 'Node.js by example';
exports.read = function() {
console.log('I am reading ' + exports.name);
}
We defined a public property and a public function. Now, we will use require to
access them:
// script.js
var book = require('./book.js');
console.log('Name: ' + book.name);
book.read();
[4]
www.it-ebooks.info
Chapter 1
We will now create another file named script.js. To test our code, we will run
node ./script.js. The result in the terminal looks like this:
So, in the end, module.exports is returned and this is what require produces.
We should be careful because if at some point we apply a value directly to exports
or module.exports, we may not receive what we need. Like at the end of the
following snippet, we set a function as a value and that function is exposed to
the outside world:
exports.name = 'Node.js by example';
exports.read = function() {
console.log('Iam reading ' + exports.name);
}
module.exports = function() { ... }
In this case, we do not have an access to .name and .read. If we try to execute node
./script.js again, we will get the following output:
[5]
www.it-ebooks.info
Node.js Fundamentals
We should also keep in mind that by default, require caches the object that is
returned. So, if we need two different instances, we should export a function. Here is
a version of the book class that provides API methods to rate the books and that do
not work properly:
// book.js
var ratePoints = 0;
exports.rate = function(points) {
ratePoints = points;
}
exports.getPoints = function() {
return ratePoints;
}
Let's create two instances and rate the books with different points value:
// script.js
var bookA = require('./book.js');
var bookB = require('./book.js');
bookA.rate(10);
bookB.rate(20);
console.log(bookA.getPoints(), bookB.getPoints());
The logical response should be 10 20, but we got 20 20. This is why it is a common
practice to export a function that produces a different object every time:
// book.js
module.exports = function() {
var ratePoints = 0;
return {
rate: function(points) {
ratePoints = points;
},
getPoints: function() {
return ratePoints;
}
}
}
[6]
www.it-ebooks.info
Chapter 1
Creating a module
Every module should live in its own directory, which also contains a metadata
file called package.json. In this file, we have set at least two properties—name
and version:
{
"name": "my-awesome-nodejs-module",
"version": "0.0.1"
}
We can place whatever code we like in the same directory. Once we publish the
module to the NPM registry and someone installs it, he/she will get the same files.
For example, let's add an index.js file so that we have two files in the package:
// index.js
console.log('Hello, this is my awesome Node.js module!');
Our module does only one thing—it displays a simple message to the console.
Now, to upload the modules, we need to navigate to the directory containing the
package.json file and execute npm publish. This is the result that we should see:
We are ready. Now our little module is listed in the Node.js package manager's site
and everyone is able to download it.
[7]
www.it-ebooks.info
Node.js Fundamentals
Using modules
In general, there are three ways to use the modules that are already created. All three
ways involve the package manager:
• We may install a specific module manually. Let's say that we have a folder
called project. We open the folder and run the following:
npm install my-awesome-nodejs-module
The manager automatically downloads the latest version of the module and
puts it in a folder called node_modules. If we want to use it, we do not need
to reference the exact path. By default, Node.js checks the node_modules
folder before requiring something. So, just require('my-awesome-nodejs-
module') will be enough.
Note the -g flag at the end. This is how we tell the manager that we want
this module to be a global one. When the process finishes, we do not have a
node_modules directory. The my-awesome-nodejs-module folder is stored
in another place on our system. To be able to use it, we have to add another
property to package.json, but we'll talk more about this in the next section.
{
"name": "another-module",
"version": "0.0.1",
"dependencies": {
"my-awesome-nodejs-module": "0.0.1"
}
}
[8]
www.it-ebooks.info
Random documents with unrelated
content Scribd suggests to you:
BOBBIN WINDER winds the thread from the spool onto the bobbin
(spool which holds thread in lower machine).
KNEE LEVER
TREADLE
10
Keep your left hand a distance from the needle to avoid this—
See how slowly you can make the needle go up and down. If the
machine runs too fast for you, you can press your right hand against
the balance wheel to slow it down.
Practice until your foot or knee can control the speed evenly from
fast to slow, without using your right hand on the balance wheel.
Slip a piece of material under the presser foot. (Your leader will have
a piece for you.) Lower the needle into the material by rolling your
right hand on the balance wheel until the needle goes down as far
as possible. Then lower the presser foot onto the material.
Let the machine run without your hands touching the material. You
will notice that it will slip and slide in many directions. To guide the
material, hold your left hand on it with your fingers curved as if you
were holding a ball in your hand. If you hold it gently, you can guide
the material as it slips under your fingers without interrupting its
movement as it is being sewn. Try it!
Your right hand will also help you to guide the material. As soon as
the machine is in motion, take your right hand off the balance
wheel. You will soon discover that you will have to practice the trick
of sewing straight.
Slow down your speed when you near the end of your material so
that you can stop when you reach the edge. Roll the balance wheel
to raise the needle—then lift the presser foot to remove the material.
Some machines have numbers next to the lever to tell you the
number of stitches per inch. If your machine does not have such
numbers, you will be able to tell the number of stitches per inch by
putting a line of stitching into a piece of material, and counting the
number of stitches sewn in a one-inch space.
Roll the balance wheel to lower the needle at the end of one of the
lines. Lower the presser foot and start the machine. Slowly stitch the
entire line (without thread), guiding your material so the needle
follows the line as much as possible. Practice stitching along a
marked line without thread, going backward and forward with both
small and large stitches.
When you can control the speed of the machine and stitch straight,
you have learned some important secrets of mother’s sewing. Soon
you will be ready to start on your first project.
You have probably learned how to follow a marked line very well by
this time. It is also important to see that you will be able to do as
well when you actually stitch with thread.
12
Enjoy good sewing habits
Hint number 1
Hint number 2
Hint number 3
13
Start to sew
If you have learned to run the sewing machine smoothly, and to
thread it correctly, you are ready to start making something useful.
A shears case
The first article you will make is a shears case. It can be used to
store your shears in your sewing box. This will help remind you that
these are special shears and should be used only for cutting fabric.
Cutting paper will make them dull.
A shears case will protect the sharp points from being damaged by
hitting other tools in the box. It will also protect your fingers when
you reach for your shears or for your other sewing tools.
Tools and supplies you will need to make the case are as follows.
Pencil
12-inch ruler
Paper shears
Fabric
Paper
Thread
Bobbin
Tailor’s chalk or tailor’s pencil
Shears
14
Measure the width of the shears by placing them on the vertical line
so that the intersection of the handles and the points of the shears
rest on the line.
Measure across the widest part of the handles. (Ask your leader to
help you read the ruler.) Label points E and G. Also measure the
width ½ inch from the point of the shears. Label these two points as
F and H.
Make a pattern for the pocket by drawing lines with your ruler, from
point E to F and G to H. Extend these lines to the full length of the
shears.
Use your ruler to measure and mark your fabric. It is most important
that you are careful to measure accurately and mark very straight
lines. Use tailor’s chalk or tailor’s pencil for marking. Then ask your
leader to check your material and your markings. They must be
perfectly marked to prevent trouble when you sew the case together
later.
Cut the fabric
15
Mark the hem on section A
A hem (material folded back on itself) is needed on the top edge of
Section A to make the top strong enough so it will not tear when the
shears are slipped into the pocket.
Measure ½ inch from the top edge of section A. Mark with pins.
Then fold the edge down so the pins lie on the outside of the fold.
Press a fold along the pins. Ask your leader to show you how to
press with a steam iron or a pressing cloth.
You have learned to stitch straight by following a line. When you
stitch this hem your presser foot not the needle will follow a line.
Place your material under the presser foot with the cut edge
touching the inside edge of the toe of the presser foot. Your leader
will show you how this is done.
Fold
Use 8 Stitches per inch
Outside edge of toe runs along cut edge
You may want to practice before stitching the hem into this part of
your shears case. Look back to page 10 if you have forgotten how to
start and end a line of stitching.
In order to neatly fold the top of section B over the shears, and also
to make the shears case more interesting, cut the flap as shown
above.
Using a ruler, draw a straight line between points a and c and points
b and d. Cut along a-c and b-d with long, even strokes.
16
Fold section A in half. Carefully put pins into the fold to mark the
center. Fold the pocket pattern, which you cut earlier, in half. Place
the center crease of the pocket pattern on the pins marking the
center of section A.
The top edge of the pattern should be even with hemline (folded
edge) of section A.
Open the pocket pattern and pin it in place. Measure the distance
between the paper pattern and the outer edge of section A at the
top and bottom of the pattern.
Trace around the pattern with tailor’s chalk or your tailor’s pencil.
Keep the chalk line very sharp, because you will be using it as a
guide for stitching the pocket.
Place section A over section B with cut edges of lower corners and
side edges matching. The hem should be folded to the inside and
chalk markings to the outside.
Pin the two pieces together with the points of the pins directed to
the side edges of the case.
Backstitch until the needle pierces folded edge, or knot the thread
according to directions on page 21. Then adjust the stitch regulator
to forward motion.
When you reach the point of the pocket, lower the needle into the
point of material, raise the presser foot, turn the material around,
lower the presser foot again, and stitch to the next point. The
presser foot needs to be raised and lowered in this manner each
time you want to turn a corner.
Stitch to the fold of the hem. When you reach the fold, 17
backstitch to the stitching line of the hem.
With your small scissors clip the threads close to the stitching line.
The side seams of the case must still be stitched together. This is
done on the outside of the case.
Place your shears case under the presser foot so that the cut edges
are even with the outside of the narrow toe. Start stitching in the
hem of section A.
When you reach each corner remember to turn your wheel by hand
so the needle goes into the material at the exact turning point. Turn
corner as you learned on page 16. Do not try to use the electricity
when reaching or turning corners until you know how to use the
machine as easily and as accurately as your mother or leader.
After you have stitched around the entire case, sew over the first
stitches you made in the hem.
Clip the threads short. (Are you remembering to put the clipped
threads into the paper bag fastened to your machine?)
Slip the shears into the pocket of the case. Then turn section B
down over the shears to find the best place to fold the flap. Mark the
fold with a pin.
Remove the shears and fold the flap on the empty case. Measure the
distance from the fold to the cut edge in several places, to be sure it
is folded evenly. Then press the fold lightly and pin into position.
Clip your threads closely, remove pins, and you have completed your
first project!
How to make your case colorful 18
Now that you have learned to measure and to use your sewing
machine accurately, you will find a great deal of enjoyment in
combining thread of a color contrasting with your material. Stitching
then becomes a decoration. If you are really able to stitch straight,
stitch each pocket twice—each row ⅛ inch apart, or the width of the
presser foot toe.
You have a pattern and have learned how simple it is to make this
handy case. Why not make a few more for gifts?
You could please your mother, or some of your friends, if you made
a case for their shears, too.
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.
ebookname.com