100% found this document useful (4 votes)
1K views

Node js By Example 1st Edition Tsonev 2024 Scribd Download

Node

Uploaded by

gjyzeballoo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
1K views

Node js By Example 1st Edition Tsonev 2024 Scribd Download

Node

Uploaded by

gjyzeballoo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Download Full ebookname - Read Now at ebookname.

com

Node js By Example 1st Edition Tsonev

https://ebookname.com/product/node-js-by-example-1st-
edition-tsonev/

OR CLICK BUTTON

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Node js Blueprints Tsonev

https://ebookname.com/product/node-js-blueprints-tsonev/

ebookname.com

D3 js By Example 1st Edition Heydt

https://ebookname.com/product/d3-js-by-example-1st-edition-heydt/

ebookname.com

Node js in Practice 1st Edition Alex R. Young

https://ebookname.com/product/node-js-in-practice-1st-edition-alex-r-
young/

ebookname.com

The Cambridge Handbook Of Policing In The United States


1st Edition Tamara Rice Lave

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

Adaptive Preferences and Women s Empowerment 1st Edition


Serene J. Khader

https://ebookname.com/product/adaptive-preferences-and-women-s-
empowerment-1st-edition-serene-j-khader/

ebookname.com

Commodity Trading Advisors Risk Performance Analysis and


Selection Wiley Finance 1st Edition Greg N. Gregoriou

https://ebookname.com/product/commodity-trading-advisors-risk-
performance-analysis-and-selection-wiley-finance-1st-edition-greg-n-
gregoriou/
ebookname.com

Introduction to computational linear algebra 1st Edition


Erhel

https://ebookname.com/product/introduction-to-computational-linear-
algebra-1st-edition-erhel/

ebookname.com

Excursions in Modern Mathematics 10th Edition Peter


Tannenbaum

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

Learn to use Node.js by creating a fully functional


social network

Krasimir Tsonev

BIRMINGHAM - MUMBAI

www.it-ebooks.info
Node.js By Example

Copyright © 2015 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, 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.

First published: May 2015

Production reference: 1190515

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78439-571-1

www.packtpub.com

www.it-ebooks.info
Credits

Author Project Coordinator


Krasimir Tsonev Harshal Ved

Reviewers Proofreaders
Danny Allen Stephen Copestake
Alex (Shurf) Frenkel Safis Editing

Commissioning Editor Indexer


Akram Hussain Priya Sane

Acquisition Editors Production Coordinator


Purav Motiwalla Shantanu N. Zagade
Llewellyn Rozario
Cover Work
Content Development Editor Shantanu N. Zagade
Shubhangi Dhamgaye

Technical Editor
Mrunal M. Chavan

Copy Editor
Vedangi Narvekar

www.it-ebooks.info
About the Author

Krasimir Tsonev is a coder with over 10 years of experience in web development.


The author of Node.js Blueprints, Packt Publishing, he works with a strong focus on
quality and usability. Krasimir is interested in delivering cutting-edge applications.
He enjoys working in the software industry and has a passion for creating and
discovering new and effective digital experiences. Right now, he is working with
technologies such as HTML5/CSS3, JavaScript, PHP, and Node.js, but he originally
started out as a graphic designer. Later, being a Flash developer, he spent several
years using ActionScript3 and frameworks such as RobotLegs. After that, as a
freelancer, he continued to deliver full-stack web services for his clients, taking care
of the graphic design and frontend and backend programming. Right now, with the
rise of mobile application development, Krasimir is enthusiastic about working on
responsive applications that target various devices. He currently lives and works
in Bulgaria. He graduated from the Technical University of Varna with both a
bachelor's and a master's degree in computer science. He loves blogging, writing
books, and giving talks on the latest trends in web development.

He has authored Node.js Blueprints, Packt Publishing (https://www.packtpub.com/


web-development/nodejs-blueprints).

I want to thank my family, who supported me in the last


several months.

www.it-ebooks.info
About the Reviewers

Danny Allen is a full-stack web developer who focuses on usability, user


experience, localization, and accessibility issues as the founder and director of
the international user experience development consultancy Wonderscore Ltd.

Skilled in a wide range of backend and frontend technologies including Python,


Django, JavaScript, Node.js, as well as HTML5/CSS3, his recent work has involved
the design and implementation of e-learning and government projects in the
United Kingdom.

His portfolio and contact details can be found at http://dannya.uk.

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.

Frenkel-Online is a project-based company that works with a number of professional


freelance consultants in Israel and abroad. Currently, their permanent staff comprises
several consultants in Israel and abroad for the company's PHP projects and a number
of specialists in other programming languages for the rest of the projects.

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

Support files, eBooks, discount offers, and more


For support files and downloads related to your book, please visit 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

Free access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view 9 entirely free books. Simply use your login credentials for
immediate access.

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

Chapter 3: Managing Assets 33


Serving files with Node.js 33
CSS preprocessing 37
Packing client-side JavaScript 39
Concatenating with Gulp 39
Modularity in the browser with RequireJS 40
Moving from Node.js to the browser with Browserify 43
Delivering HTML templates 45
Defining the templates in script tags 45
Loading the template externally 46
Writing HTML inside the JavaScript 46
Precompiling templates 47
Summary 49
Chapter 4: Developing the Model-View-Controller Layers 51
Evolving the current setup 51
Directory structure 52
Forming the main server handlers 52
Implementing the router 54
Introducing Ractive.js 59
Constructing the entry point of the application 61
Defining a controller 62
Managing our views 64
Creating a model 65
Summary 68
Chapter 5: Managing Users 69
Working with the MongoDB database 69
Installing MongoDB 70
Running MongoDB 70
Connecting to the database server 71
Extending the code from the previous chapter 72
Updating our base model class 72
Updating page navigation and routing 74
Registering a new user 75
Updating the frontend 75
Updating the backend API 78
User authentication with sessions 81
Managing a user's profile 86
Summary 89

[ ii ]

www.it-ebooks.info
Table of Contents

Chapter 6: Adding Friendship Capabilities 91


Finding friends 91
Adding the search page 91
Writing the model 94
Fetching friends from the database 97
Marking users as friends 99
Displaying the linked users on the Profile page 102
Summary 104
Chapter 7: Posting Content 105
Posting and storing text 105
Adding a form to post text messages 105
Introducing the content's model 106
Updating the controller of the home page 107
Storing content in the database 109
Showing the user's feed 110
Posting files 114
Summary 120
Chapter 8: Creating Pages and Events 121
Refactoring the API 121
Adding a form to create pages 124
Creating a record in the database 126
Showing the currently added pages 129
Showing a specific page 130
Posting a comment to a page 133
Showing the comments 135
Managing events attached to a particular page 137
Summary 140
Chapter 9: Tagging, Sharing, and Liking 141
Selecting friends and sending their IDs to the backend 141
Storing the tagged users and displaying them in the user's feed 143
Sharing a post 147
Liking posts and counting the number of likes 151
Showing the number of likes 154
Summary 155

[ iii ]

www.it-ebooks.info
Table of Contents

Chapter 10: Adding Real-time Chat 157


Getting to know WebSockets 157
Bringing Socket.IO to the project 159
Preparing the UI of the chat area 161
Exchanging messages between the client and the server 164
Sending messages to the user's friends only 169
Customizing the output of the chat 172
Summary 175
Chapter 11: Testing the User Interface 177
Introducing the basic testing toolset 177
The testing framework 177
The assertion library 178
Runner 178
Preparing our project to run tests 178
Running our test with PhantomJS 184
Testing user registration 185
Simulating user interaction 185
Filling and submitting the registration form 186
Tweaking the code's execution order 188
Listening to the form-submitted event 190
Testing with DalekJS 191
Installing DalekJS 191
Using the DalekJS API 192
Summary 194
Index 195

[ 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.

What this book covers


Chapter 1, Node.js Fundamentals, teaches the basics of Node.js, what stands behind the
technology, and its module management system and package manager.

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.

Chapter 4, Developing the Model-View-Controller Layers, is about the basic structure of


our application. We will create classes for views, models, and controllers. In the next
few chapters, we will use these classes as a base.

[v]

www.it-ebooks.info
Preface

Chapter 5, Managing Users, is about implementing user registration, authorization,


and profile management.

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.

What you need for this book


The book is based on Node.js version 0.10.36. We will also use MongoDB (http://
www.mongodb.org/) as a database and Ractive.js (http://www.ractivejs.org/) as
a client-side framework.

Who this book is for


If you have knowledge of JavaScript and want to see how you can use it in the
backend, this book is for you. It will lead you through the creation of a fairly complex
social network. You will learn how to work with a database and create real-time
communication channels.

[ 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."

A block of code is set as follows:


<li class="right"><a on-click="goto:logout">Logout</a></li>
<li class="right"><a on-click="goto:profile">Profile</a></li>
<li class="right"><a on-click="goto:find-friends">Find
friends</a></li>

Any command-line input or output is written as follows:


sudo apt-get update
sudo apt-get install nodejs
sudo apt-get install npm

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."

Tips and tricks appear like this.

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.

To send us general feedback, simply send an e-mail to feedback@packtpub.com,


and mention the book title via the subject of your message.

[ 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.

Downloading the example code


You can download the example code files for all Packt books you have purchased
from your account at http://www.packtpub.com. If you purchased this book
elsewhere, you can visit http://www.packtpub.com/support and register to have
the files e-mailed directly to you.

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.

Please contact us at copyright@packtpub.com with a link to the suspected


pirated material.

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:

• Node.js building blocks


• The main capabilities of the environment
• The package management of Node.js

Understanding the Node.js architecture


Back in the days, Ryan was interested in developing network applications. He found
out that most high performance servers followed similar concepts. Their architecture
was similar to that of an event loop and they worked with nonblocking input/output
operations. These operations would permit other processing activities to continue
before an ongoing task could be finished. These characteristics are very important if
we want to handle thousands of simultaneous requests.

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

Ryan needed something that is event-loop-based and which works fast. As he


pointed out in one of his presentations, big companies such as Google, Apple, and
Microsoft invest a lot of time in developing high performance JavaScript engines.
They have become faster and faster every year. There, event-loop architecture is
implemented. JavaScript has become really popular in recent years. The community
and the hundreds of thousands of developers who are ready to contribute made
Ryan think about using JavaScript. Here is a diagram of the Node.js architecture:

In general, Node.js is made up of three things:

• V8 is Google's JavaScript engine that is used in the Chrome web


browser (https://developers.google.com/v8/)
• A thread pool is the part that handles the file input/output operations.
All the blocking system calls are executed here (http://software.schmorp.
de/pkg/libeio.html)
• The event loop library (http://software.schmorp.de/pkg/libev.html)

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

Running Node.js server


Node.js is a command-line tool. After installing it, the node command will be
available on our terminal. The node command accepts several arguments, but the
most important one is the file that contains our JavaScript. Let's create a file called
server.js and put the following code inside:

var http = require('http');


http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(9000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:9000/');

Downloading the example code


You can download the example code files from your account at
http://www.packtpub.com for all the Packt Publishing books
that you have purchased. If you purchased this book elsewhere, you
can visit http://www.packtpub.com/support and register to
have the files e-mailed directly to you.

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.

The result that we will get in a browser is as follows:

Defining and using modules


JavaScript as a language does not have mechanisms to define real classes. In fact,
everything in JavaScript is an object. We normally inherit properties and functions
from one object to another. Thankfully, Node.js adopts the concepts defined by
CommonJS—a project that specifies an ecosystem for JavaScript.

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:

Along with exports, we also have module.exports available. There is a difference


between the two. Look at the following pseudocode. It illustrates how Node.js
constructs our modules:
var module = { exports: {} };
var exports = module.exports;
// our code
return module.exports;

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:

To avoid such issues, we should stick to one of the two options—exports or


module.exports—but make sure that we do not have both.

[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;
}
}
}

Now, we should also have require('./book.js')() because require returns a


function and not an object anymore.

[6]

www.it-ebooks.info
Chapter 1

Managing and distributing packages


Once we understand the idea of require and exports, we should start thinking
about grouping our logic into building blocks. In the Node.js world, these blocks are
called modules (or packages). One of the reasons behind the popularity of Node.js is
its package management.

Node.js normally comes with two executables—node and npm. NPM is a


command-line tool that downloads and uploads Node.js packages. The official
site, https://npmjs.org/, acts as a central registry. When we create a package
via the npm command, we store it there so that every other developer may use it.

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.

• The installation of modules globally is a common practice, especially if


we talk about command-line tools made with Node.js. It has become an
easy-to-use technology to develop such tools. The little module that we
created is not made as a command-line program, but we can still install
it globally by running the following code:
npm install my-awesome-nodejs-module -g

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.

• The resolving of dependencies is one of the key features of the package


manager of Node.js. Every module can have as many dependencies as you
want. These dependences are nothing but other Node.js modules that were
uploaded to the registry. All we have to do is list the needed packages in the
package.json file:

{
"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).

STITCH REGULATOR makes stitches small or large. Also adjusts the


machine to move your material forward or backward.

CLOTH GUIDE ATTACHMENT helps to stitch straight seams.

Types of control levers


FOOT CONTROL

KNEE LEVER
TREADLE

How to use the sewing machine

Is your chair the right height?

• Can you see the needle easily as it moves up and down?


• Are you able to reach behind the needle?
• Can you rest your arms on the table?
• Do your feet touch the floor?
If you cannot see the needle or rest your arms on the table, you will
need a taller chair or something to sit on to raise you up a bit. If
your feet do not touch the floor (after you are sitting in the position
to see the needle) and your machine has a foot control you will have
to find a sturdy box. It should be large enough to rest both of your
feet, as well as the foot control from the machine.

10

How to start and stop the machine

With your machine unthreaded and the presser foot raised, it is


ready for you to start. Place your right hand on the balance wheel.
(It will help you to start the machine in motion.)

Keep your left hand a distance from the needle to avoid this—

How to speed up and slow down

Place your foot or knee on the control or treadle.

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.

How to stitch correctly

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.

How to use the stitch regulator

If your sewing machine has a lever which makes it sew backward,


try to use it now. Move the stitch regulator up as far as it will go. As
you start the machine you will see it moving backward. In order to
stitch forward again, push the lever back down as far as it will go. As
you will learn in your projects, you will always have to sew 11
very slowly and carefully when you sew backward in order to
do it nicely.
Another reason the stitch regulator is on your machine is to make
the stitches larger or smaller for you, whichever is best for the
material with which you are working.

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.

How to practice stitching

Mark some straight and curved lines on your piece of material.


(Paper may also be used but it dulls the needle; material is best.)

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.

How to thread the machine

Would you like to be able to thread the machine as easily as your


leader threads it? Ask her to do it very slowly for you so you can
learn it from her. Watch closely as she hooks the thread onto every
finger of each thread guide until she finally reaches the needle. She
will also show you where the bobbin hides (remember this is the flat
spool in the lower part of the machine) and how you will get its
thread to the top of the machine.
After you have threaded the machine be sure to have your leader
check it before you try to sew. If you want the machine to “work like
magic” you will have to have it threaded correctly.

Stitching with a threaded machine

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

The first important hint to know


is—“Join the Clean Clan Club” whenever you sew!

Hands freshly washed and nails clean, too


will help keep your projects looking like new.

Clean clothes—“a must” while handling cloth,


for fear some dust and grime may rub off.

Last of all—your table must gleam


to protect nice materials from soil unseen.

So—Clean Hands, Clean Clothes, Clean Table, too,


is an important trick for you.

Hint number 2

“The Clean Clan Clubs” can boastful be


of unsoiled projects, delightful to see.

But here’s another hint for you—


to keep you from wrinkling your fabrics so new.

Your lap’s too small and too far away


to hold your project by night or by day.

But—your table clean would love to hold


the bulk of that fabric, while you pin that fold.
So,—trick number 2, in this sewing trade
is—work on a table to get your projects made.

Hint number 3

Here’s one last, special hint for you—


and something easy we would like you to do.

Look at yourself—as you start to sew.


How do you sit? And how are your feet below?

Think of your posture—it’s no chore—


to keep your back straight, with both feet on the floor.

You won’t get tired so quickly then


and you’ll enjoy stitching again and again.

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.

The first article you will make is a “Shears Case”

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.

What you will learn

• To recognize the feel and appearance of felt or nonwoven


interfacing.
• To choose and buy pretty material and thread.
• To read ruler measurements.
• To make a pattern according to measurements.
• To pin a pattern to the material.
• To handle the shears when cutting material.
• To use tailor’s chalk or a tailor’s pencil for marking around the
pattern.
• To use the stitch regulator for backstitching and adjusting the
size of stitches.
• To use the toe of the presser foot as a marked line for stitching
straight.
• To make a hem and stitch it.

What you will do first

To make a shears case you will need to buy felt or nonwoven


interfacing (suit-weight), thread, and tailor’s chalk or pencil.

If your shears are 8 inches or less in length, the felt swatches (9


inches wide and 12 inches long) sold in many stores are a good buy.
If your shears are over 8 inches long see page 14 for directions. Ask
your leader or your mother to help you decide how much fabric you
will need.

If it is easy for you to stitch straight, try a color of thread which is


different from your material to add color to your case.
If you are still having difficulty stitching on a straight line, it would
be better to use thread which matches your material because
mistakes will be less easy to see. You can use either regular or
heavy duty thread.

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

How to make the shears case

Make a paper pattern

Measure the length of your shears on a piece of paper. Mark this


length with lines AB and CD. Then draw a vertical line between these
two lines by placing a ruler on the lines as shown.

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.

Mark the fabric; follow the illustration

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

Since cutting material, especially heavy material like felt or


nonwoven interfacing, is different than cutting paper, practice on
some scraps of material before you cut the fabric for the case. You
will have the best cut edge if you open the shears wide and take
long even strokes in cutting. Do not close the points of the shears
until you reach the end of the pattern or the material. Cut the piece
of fabric along the marked lines.

ALWAYS HOLD AND CUT MATERIAL ON THE TABLE

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.

Shape the flap of section B

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.

Measure ½ inch from the sides of fabric piece B—points a and b.


Then measure 2 inches from the top of section B—points c and d.

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

Mark the pocket on section A

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.

Get the pocket ready to stitch


To make the pocket, you will be stitching section A and section B
together. Since two thicknesses of fabric are more bulky than a
single thickness, it will be necessary to learn how to pin them
together so they will not slip when you are stitching them.

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.

Machine stitch the pocket


Adjust the stitch regulator to 8 stitches per inch. Lower the needle
on the stitched hemline of section A. Lower the presser foot after
the threads have been drawn between the toes to the back of the
machine.

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.

Stitch following the line you have marked, stitching on it as much as


possible. Apply little pressure onto the knee lever or foot pedal so
the machine will not move too fast.

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.

Sew sections A and B together

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?)

Change the top of section B into a flap


In order to keep the upper part of section B in a folded position so it
will keep the shears in the pocket, you need to add one more row of
stitching.

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.

Machine stitch ⅛ inch from the fold of the flap, backstitching up to


the stitching line, and then moving forward.

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.

Barbecue placemats or traveling kit


This project will give you more practice in using the parts of the
sewing machine you have learned to use in making your shears
case. You may choose to make either placemats or a traveling kit or
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like