Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Node.js Blueprints
Node.js Blueprints

Node.js Blueprints: Develop stunning web and desktop applications with the definitive Node.js

Arrow left icon
Profile Icon Krasimir Stefanov Tsonev
Arrow right icon
$24.99 $36.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7 (10 Ratings)
eBook Jun 2014 268 pages 1st Edition
eBook
$24.99 $36.99
Paperback
$60.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Krasimir Stefanov Tsonev
Arrow right icon
$24.99 $36.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7 (10 Ratings)
eBook Jun 2014 268 pages 1st Edition
eBook
$24.99 $36.99
Paperback
$60.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$24.99 $36.99
Paperback
$60.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Node.js Blueprints

Chapter 2. Developing a Basic Site with Node.js and Express

In the previous chapter, we learned about common programming paradigms and how they apply to Node.js. In this chapter, we will continue with the Express framework. It's one of the most popular frameworks available and is certainly a pioneering one. Express is still widely used and several developers use it as a starting point.

Getting acquainted with Express

Express (http://expressjs.com/) is a web application framework for Node.js. It is built on top of Connect (http://www.senchalabs.org/connect/), which means that it implements middleware architecture. In the previous chapter, when exploring Node.js, we discovered the benefit of such a design decision: the framework acts as a plugin system. Thus, we can say that Express is suitable for not only simple but also complex applications because of its architecture. We may use only some of the popular types of middleware or add a lot of features and still keep the application modular.

In general, most projects in Node.js perform two functions: run a server that listens on a specific port, and process incoming requests. Express is a wrapper for these two functionalities. The following is basic code that runs the server:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain&apos...

Installing Express

There are two ways to install Express. We'll will start with the simple one and then proceed to the more advanced technique. The simpler approach generates a template, which we may use to start writing the business logic directly. In some cases, this can save us time. From another viewpoint, if we are developing a custom application, we need to use custom settings. We can also use the boilerplate, which we get with the advanced technique; however, it may not work for us.

Using package.json

Express is like every other module. It has its own place in the packages register. If we want to use it, we need to add the framework in the package.json file. The ecosystem of Node.js is built on top of the Node Package Manager. It uses the JSON file to find out what we need and installs it in the current directory. So, the content of our package.json file looks like the following code:

{
  "name": "projectname",
  "description": "description&quot...

Managing routes

The input of our application is the routes. The user visits our page at a specific URL and we have to map this URL to a specific logic. In the context of Express, this can be done easily, as follows:

var controller = function(req, res, next) {
  res.send("response");
}
app.get('/example/url', controller);

We even have control over the HTTP's method, that is, we are able to catch POST, PUT, or DELETE requests. This is very handy if we want to retain the address path but apply a different logic. For example, see the following code:

var getUsers = function(req, res, next) {
  // ...
}
var createUser = function(req, res, next) {
  // ...
}
app.get('/users', getUsers);
app.post('/users', createUser);

The path is still the same, /users, but if we make a POST request to that URL, the application will try to create a new user. Otherwise, if the method is GET, it will return a list of all the registered members. There is also a method, app...

Handling dynamic URLs and the HTML forms

The Express framework also supports dynamic URLs. Let's say we have a separate page for every user in our system. The address to those pages looks like the following code:

/user/45/profile

Here, 45 is the unique number of the user in our database. It's of course normal to use one route handler for this functionality. We can't really define different functions for every user. The problem can be solved by using the following syntax:

var getUser = function(req, res, next) {
  res.send("Show user with id = " + req.params.id);
}
app.get('/user/:id/profile', getUser);

The route is actually like a regular expression with variables inside. Later, that variable is accessible in the req.params object. We can have more than one variable. Here is a slightly more complex example:

var getUser = function(req, res, next) {
  var userId = req.params.id;
  var actionToPerform = req.params.action;
  res.send("User (" + userId...

Returning a response

Our server accepts requests, does some stuff, and finally, sends the response to the client's browser. This can be HTML, JSON, XML, or binary data, among others. As we know, by default, every middleware in Express accepts two objects, request and response. The response object has methods that we can use to send an answer to the client. Every response should have a proper content type or length. Express simplifies the process by providing functions to set HTTP headers and sending content to the browser. In most cases, we will use the .send method, as follows:

res.send("simple text");

When we pass a string, the framework sets the Content-Type header to text/html. It's great to know that if we pass an object or array, the content type is application/json. If we develop an API, the response status code is probably going to be important for us. With Express, we are able to set it like in the following code snippet:

res.send(404, 'Sorry, we cannot find...

The example-logging system

We've seen the main features of Express. Now let's build something real. The next few pages present a simple website where users can read only if they are logged in. Let's start and set up the application. We are going to use Express' command-line instrument. It should be installed using npm install -g express-generator. We create a new folder for the example, navigate to it via the terminal, and execute express --css less site. A new directory, site, will be created. If we go there and run npm install, Express will download all the required dependencies. As we saw earlier, by default, we have two routes and two controllers. To simplify the example, we will use only the first one: app.use('/', routes). Let's change the views/index.jade file content to the following HTML code:

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    h1= title
    hr
    p...

Getting acquainted with Express


Express (http://expressjs.com/) is a web application framework for Node.js. It is built on top of Connect (http://www.senchalabs.org/connect/), which means that it implements middleware architecture. In the previous chapter, when exploring Node.js, we discovered the benefit of such a design decision: the framework acts as a plugin system. Thus, we can say that Express is suitable for not only simple but also complex applications because of its architecture. We may use only some of the popular types of middleware or add a lot of features and still keep the application modular.

In general, most projects in Node.js perform two functions: run a server that listens on a specific port, and process incoming requests. Express is a wrapper for these two functionalities. The following is basic code that runs the server:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');...
Left arrow icon Right arrow icon

Description

A straightforward, practical guide containing step-by-step tutorials that will push your Node.js programming skills to the next level. If you are a web developer with experience in writing client-side JavaScript and want to discover the fascinating world of Node.js to develop fast and efficient web and desktop applications, then this book is for you.

What you will learn

  • Explore design patterns in Node.js
  • Build solid architectures by following testdriven development
  • Look beyond web applications and create your own desktop app with Node.js
  • Develop single page applications using Node.js with AngularJS, Ember.js, and Backbone.js
  • Master the Express framework and build a complete site with a real database
  • Create a realtime and fully functional online chat application with Socket.IO
  • Utilize the enormous range of Grunt and Gulp plugins

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 16, 2014
Length: 268 pages
Edition : 1st
Language : English
ISBN-13 : 9781783287345
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jun 16, 2014
Length: 268 pages
Edition : 1st
Language : English
ISBN-13 : 9781783287345
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 170.97
Node Cookbook: Second Edition
$54.99
Node.js Blueprints
$60.99
Mastering Node.js
$54.99
Total $ 170.97 Stars icon
Banner background image

Table of Contents

13 Chapters
1. Common Programming Paradigms Chevron down icon Chevron up icon
2. Developing a Basic Site with Node.js and Express Chevron down icon Chevron up icon
3. Writing a Blog Application with Node.js and AngularJS Chevron down icon Chevron up icon
4. Developing a Chat with Socket.IO Chevron down icon Chevron up icon
5. Creating a To-do Application with Backbone.js Chevron down icon Chevron up icon
6. Using Node.js as a Command-line Tool Chevron down icon Chevron up icon
7. Showing a Social Feed with Ember.js Chevron down icon Chevron up icon
8. Developing Web App Workflow with Grunt and Gulp Chevron down icon Chevron up icon
9. Automate Your Testing with Node.js Chevron down icon Chevron up icon
10. Writing Flexible and Modular CSS Chevron down icon Chevron up icon
11. Writing a REST API Chevron down icon Chevron up icon
12. Developing Desktop Apps with Node.js Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7
(10 Ratings)
5 star 70%
4 star 30%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Rakesh Aug 08, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
There are hardly any good books on node.js available in market, but this is an exception. I went through blogs and posts just to find a good node.js book.Since i am pretty excited about learning node.js, i did not want my experience to be soured by "not so good" book. I had almost given up my search until i found this one. Reading it is a breeze and you do not want to put it down. Examples are mentioned very neatly and they are easy to understand. Just go through car example in first few pages and you will understand about modules, events, promises etc. My request to author would be to write more such books.
Amazon Verified review Amazon
Amazon Customer Jul 29, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book, Nodejs-Blueprints is divided up well into 12 chapters. Each of these chapters demonstrates a practical project showing the developer how to utilize todays Javascript language and frameworks in conjunction with node.js to develop modern web based applications.From the Preface of the book, "The book is for intermediate developers. It teaches you how to use popular Node.js libraries and frameworks. So, good JavaScript knowledge is required."This is certainly true, you need to have an awareness and understanding of javascript before tackling the examples. For example in Chapter 3, "Writing a Blog Application with Node.js and AngularJS" the author introduces the fundamentals of AngularJS but only within the confines of the space of this book and context of this example. A previous understanding of AngularJS would be of great benefit here.The publishers do provide a separate code sample file for download, as most programming books do these days. Although the code samples should be downloaded, it is preferable to type the code into your editor to become more experienced at writing error free code.Chapter 1 introduces Node.js, a javascript technology, and a number of programming paradigms specifically applicable to node.js.Of specific relevance is the architectural discussion and the very clear demonstration of developing modular code. This becomes important in the later chapters of testing and building your application.Chapter 2 introduces the first of the example applications, a basic web site using nodejs and ExpressJS.As other reviewers, and the author, have noted there are differences between the book and the current technology implementation of Express.js and Node.js. The author will provide an updated chapter highlighting the differences.Chapters 3 & 4 introduce the fundamentals of real world applications developed using Node.js. A blogging application and a Live Chat application. In particular the live chat application highlights the "real time" capabilities of Node.js and socket.io.Chapters 5 through 7 continue to introduce and develop various types of applications, from Social Network feeds to Command Line tools.However, for me personally, Chapters 8 & 9 in particular delivered the most value in the book.Complexity in modern web application development has increased significantly due to the newer programming technologies available, modern architectural styles (ie modular code, even in CSS with LESS and SASS), dependency management during the build process, automated build, test driven development and so forth. Each of these aspects is critical to a successful deployment of your application.Reading the chapters on 'build' and 'test' was like lifting a dark cloud of confusion. The introduction to build tools Grunt & Gulp in Chapter 8 and incremental additions to the base code made it very clear and easy to follow what was happening, right down to triggering the build by watching for changes to the code files. By simply following the code samples in the book I was able to set up automated testing using Grunt without errors.Introduction of the test suites Jasmine and Mocha in Chapter 9 was equally as clear and concise, incrementally building on a basic script. The introduction of testing using a "headless browser" in the form of PhantomJS, allows the developer to test page visits, button clicks and sending of forms.Chapter 9 closes out by introducing DalekJS, a Nodejs module which allows developers to test real world browsers, such as Chrome, Firefox and Internet Explorer. As the user has choice of their web browser today, it is important to be able to test your code in as many environments as possible.Gaining a thorough understanding of the build and test processes as described by these 2 chapters will provide a solid foundation for writing great web applications.Chapter 10 explores the world of modular CSS by firstly explaining and then introducing CSS Pre-Processors. There are a number available today and the most popular are introduced.REST stands for Representational State Transfer and it is an architectural principle of the Web. In most of the cases, the server has resources that need to be created, fetched, updated, or deleted. The REST APIs provide mechanisms to perform all these operations.Chapter 11 introduces and develops a restful API to manage an online library. As with all previous chapters, an incremental approach to developing the scripts and databases leads to a working sample of REST based web application.The last chapter, chapter 12, highlights the development of a desktop program. Nodejs is typically known for its web based applications, but in this chapter a more traditional desktop program to read files on the local computer is developed using node-webkit.Overall I would rate the book 5 stars. I found the incremental approach to the code samples very easy to follow and although I did not build all the sample applications, those I did develop, I did so without errors.As noted above the chapters on build and test, such a critical part of todays web development world, were very clearly explained and demonstrated. This made this book a very valuable resource in my development tool set and one I shall keep close by.Publisher Link : http://www.packtpub.com/nodejs-blueprints/book
Amazon Verified review Amazon
Charriere Jul 22, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I just finished reading the book "Node.js Blueprints". If you are discovering NodeJS is a very good addition to your research. After a brief review of the fundamentals, the author gives you recipes on various topics, especially how to use Angular with Node and a database, or create a chat with Socket.IO, etc.I like very much the chapter about Node as Command-line Tool, where the author explains how to connect to Flickr with OAuth.You can read an introduction about Grunt and Gulp, again the fundamentals : how to minify your code, watching for changes, testing, ... Even, how to develop an desktop application with Node.I think this book is a great corpus of representative samples of what you can do with Node.
Amazon Verified review Amazon
Norbert Varga Aug 07, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I chose this book because I like Javascript very much, but I'm not familiar with Node.js, so it was an interesting read.The author chose the best way to teach Node.js (in fact, I think this is the best way to teach anything, and keep the reader's attention): by real-life examples. These examples are very good, they show the reader how to deal with real-life problems like interacting with a MySQL database, implementing a blog engine, implementing a REST API, and creating desktop apps.I definitely recommend this book to everyone who know Javascript well, and want to know more about Node.js.
Amazon Verified review Amazon
Theodore Jul 22, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Node.js Blueprints is addressed to people who know JavaScript and want to use it from the server side too.The book starts with a chapter on some programming paradigms that are currently used on the Node.js land. Patterns such as inter-module communication or how the asynchronous nature of Node works.The following chapters are mainly concerned with the most important libraries on the Node.js ecosystem. The first library the author chose to present us is Express (probably expected). We go through a basic site while learning Express. The author, along with every JS library, walks us through a tutorial with a sample web application. He continues with chapters on Angular and sample blog, socket.io and chat app, backbone and to-do app, ember and social feed app.Apart from the above libraries there is material on automation, testing, dynamics CSS, REST API and Node.js desktop apps.Suitable for those who want a start on Node.js and its ecosystem, Node.js Blueprints is a pretty good book. The author’s approach with example web apps on each library is very good. Every chapter is clear while after finishing it you have learned what you need to start and decide whether you want to dive further into.Furthermore, the code of the book is available from Packt Publishing. Care, though, since there are some (understandable) errors.Recommended!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.