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
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7 (10 Ratings)
Paperback Jun 2014 268 pages 1st Edition
eBook
Can$42.99 Can$61.99
Paperback
Can$77.99
Subscription
Free Trial
Arrow left icon
Profile Icon Krasimir Stefanov Tsonev
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7 (10 Ratings)
Paperback Jun 2014 268 pages 1st Edition
eBook
Can$42.99 Can$61.99
Paperback
Can$77.99
Subscription
Free Trial
eBook
Can$42.99 Can$61.99
Paperback
Can$77.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781783287338
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jun 16, 2014
Length: 268 pages
Edition : 1st
Language : English
ISBN-13 : 9781783287338
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 Can$6 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 Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 217.97
Mastering Node.js
Can$69.99
Node.js Blueprints
Can$77.99
Node Cookbook: Second Edition
Can$69.99
Total Can$ 217.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.