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
Conferences
Free Learning
Arrow right icon
Node Cookbook
Node Cookbook

Node Cookbook: Over 50 recipes to master the art of asynchronous server-side JavaScript using Node with this book and ebook.

Arrow left icon
Profile Icon David Mark Clements
Arrow right icon
€8.99 €28.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (9 Ratings)
eBook Jul 2012 342 pages 1st Edition
eBook
€8.99 €28.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon David Mark Clements
Arrow right icon
€8.99 €28.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (9 Ratings)
eBook Jul 2012 342 pages 1st Edition
eBook
€8.99 €28.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €28.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.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 Cookbook

Chapter 2. Exploring the HTTP Object

In this chapter we will cover:

  • Processing POST data

  • Handling file uploads

  • Using Node as an HTTP client

  • Implementing download throttling

Introduction


In the previous chapter, we used the http module to create a web server. Now we're going to look into some associated use cases beyond simply pushing content from server to client. The first three recipes will explore how to receive data via client-initiated HTTP POST (and PUT) requests, and in the final recipe we'll demonstrate how to throttle a stream of outbound data.

Processing POST data


If we want to be able to receive POST data, we have to instruct our server on how to accept and handle a POST request. In PHP we could access our POST values seamlessly with $_POST['fieldname'], because it would block until an array value was filled. By contrast, Node provides low-level interaction with the flow of HTTP data allowing us to interface with the incoming message body as a stream, leaving it entirely up to the developer to turn that stream into usable data.

Getting ready

Let's create a server.js file ready for our code, and an HTML file called form.html, containing the following code:

<form method=post>
<input type=text name=userinput1><br>
<input type=text name=userinput2><br>
<input type=submit>
</form>

Note

For our purposes, we'll place form.html in the same folder as server.js, though this is not generally a recommended practice. Usually, we should place our public code in a separate folder from our server code....

Handling file uploads


We cannot process an uploaded file in the same way we process other POST data. When a file input is submitted in a form, the browser processes the file into a multipart message.

Multipart was originally developed as an email format allowing multiple pieces of mixed content to be combined into one message. If we intuitively attempted to receive the upload as a stream and write it to a file, we would have a file filled with multipart data instead of the file or files themselves. We need a multipart parser, the writing of which is more than a recipe can cover. So instead we'll be using the well-known and battle-tested formidable module to convert our upload data into files.

Getting ready

Let's create a new uploads directory for storing uploaded files and get ready to make modifications to our server.js file from the previous recipe.

We'll also need to install formidable as follows:

npm install formidable@1.x.x

Finally, we'll make some changes to our form.html from the...

Using Node as an HTTP client


The HTTP object doesn't just provide server capabilities, it also affords us with client functionality. In this task, we're going to use http.get with process to fetch external web pages dynamically via the command line.

Getting ready

We are not creating a server, so in the naming convention we should use a different name for our new file, let's call it fetch.js.

How to do it...

http.request allows us to make requests of any kind (for example, GET, POST, DELETE, OPTION, and so on), but for GET requests we can use the short-hand http.get method as follows:

var http = require('http');
var urlOpts = {host: 'www.nodejs.org', path: '/', port: '80'};
http.get(urlOpts, function (response) {
response.on('data', function (chunk) {
console.log(chunk.toString());
});
});

Essentially we're done.

node fetch.js

If we run the preceding command, our console will output the HTML of nodejs.org. However, let's pad it out a bit with some interactivity and error handling as shown in...

Implementing download throttling


For incoming streams, Node provides pause and resume methods, but not so for outbound streams. Essentially, this means we can easily throttle upload speeds in Node but download throttling requires a more creative solution.

Getting ready

We'll need a new server.js along with a good-sized file to serve. With the dd command-line program, we can generate a file for testing purposes.

dd if=/dev/zero of=50meg count=50 bs=1048576

This will create a 50 MB file named 50meg which we'll be serving.

Note

For a similar Windows tool that can be used to generate a large file, check out http://www.bertel.de/software/rdfc/index-en.html.

How to do it...

To keep things as simple as possible our download server will serve just one file, but we'll implement it in a way which would allow us to easily plug in some router code to serve multiple files. First, we will require our modules and set up an options object for file and speed settings.

var http = require('http');
var fs = require...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Packed with practical recipes taking you from the basics to extending Node with your own modules
  • Create your own web server to see Node's features in action
  • Work with JSON, XML, web sockets, and make the most of asynchronous programming

Description

The principles of asynchronous event-driven programming are perfect for today's web, where efficient real-time applications and scalability are at the forefront. Server-side JavaScript has been here since the 90's but Node got it right. With a thriving community and interest from Internet giants, it could be the PHP of tomorrow. "Node Cookbook" shows you how to transfer your JavaScript skills to server side programming. With simple examples and supporting code, "Node Cookbook" talks you through various server side scenarios often saving you time, effort, and trouble by demonstrating best practices and showing you how to avoid security faux pas. Beginning with making your own web server, the practical recipes in this cookbook are designed to smoothly progress you to making full web applications, command line applications, and Node modules. Node Cookbook takes you through interfacing with various database backends such as MySQL, MongoDB and Redis, working with web sockets, and interfacing with network protocols, such as SMTP. Additionally, there are recipes on correctly performing heavy computations, security implementations, writing, your own Node modules and different ways to take your apps live.

Who is this book for?

If you have some knowledge of JavaScript and want to build fast, efficient, scalable client-server solutions, then Node Cookbook is for you. Experienced users of Node will improve their skills although even if you have not worked with Node before, these practical recipes will make it easy to get started.

What you will learn

  • Write and publish your own modules
  • Interface with various databases
  • Work with streams of data
  • Handle file uploads and POST data
  • Use the Express framework to accelerate the development of your applications
  • Learn about security, encryption, and authentication techniques

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 25, 2012
Length: 342 pages
Edition : 1st
Language : English
ISBN-13 : 9781849517195
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 : Jul 25, 2012
Length: 342 pages
Edition : 1st
Language : English
ISBN-13 : 9781849517195
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 117.97
Node Web Development - Second Edition
€37.99
Node Cookbook
€37.99
Mastering Node.js
€41.99
Total 117.97 Stars icon
Banner background image

Table of Contents

10 Chapters
Making a Web Server Chevron down icon Chevron up icon
Exploring the HTTP Object Chevron down icon Chevron up icon
Working with Data Serialization Chevron down icon Chevron up icon
Interfacing with Databases Chevron down icon Chevron up icon
Transcending AJAX: Using WebSockets Chevron down icon Chevron up icon
Accelerating Development with Express Chevron down icon Chevron up icon
Implementing Security, Encryption, and Authentication Chevron down icon Chevron up icon
Integrating Network Paradigms Chevron down icon Chevron up icon
Writing Your Own Node Modules Chevron down icon Chevron up icon
Taking It Live Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(9 Ratings)
5 star 44.4%
4 star 33.3%
3 star 0%
2 star 22.2%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Doug Duncan Oct 21, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Node Cookbook by David Mark Clements is one of the better tech books I've read recently. David writes in a way that is easy to read and follow. He takes the reader on a journey from creating their first web server to securing their application, from data serialization and storage to deploying to a production server and everything in between.This book goes beyond your typical cookbook style of here's a problem and here's your solution. David does a great job of explaining what and why you are doing something, and then he goes on and expands on the subject in the "There's more..." sections, giving you deeper insight into the topic or showing different ways of doing things. Another thing that is different in this book, compared to other cookbooks, is that some chapters have the reader build on topics from earlier sections of the chapter (or even earlier chapters) to give you a more complete solution.A couple of my favorite chapters were 5 and 8. Chapter 5 gives recipes on storing data in both traditional databases (MySQL) and newer alternative datastores (MongoDB, CouchDB and Redis). Chapter 8 shows that node is not just another web server. It gives recipes for sending email and SMS message as well as for using Node as an SMTP server and how you can set up multiple web sites on a single server.Chapter 7, which deals with security, is another important chapter in the book. It discusses not only basic and digest authentication, but also shows how to set up and communicate with Node over HTTPS. The final recipe discusses cross-site request forgery.This is a book that I wished would have been out a year and a half ago when I was setting up my first Node solution. It is a welcome addition to my library and one that I will highly recommend to coworkers.Updated for the Second Edition:David has updated the book and it's just as good, if not better than the first edition. He's updated the text and source code to use newer packages. In addition to these updates and an added recipe in a chapter or two, David has also added a new chapter covering Stream Processing with four new recipes.The book still stays at the 5 stars I gave the first edition, and I'm looking forward to reading anything else the authors puts out.
Amazon Verified review Amazon
Kevin Barnett Dec 19, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I haven't finished yet but so far all examples are good and easy to follow. Would recommend to anyone looking to use Node for the first time (you must be the type that learns by example). Also, an understanding of javascript is must.
Amazon Verified review Amazon
Juanjo Fernandez Oct 28, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Before starting the review, I must say that I have not read the book in depth. I have one week with it, but I feel that is enough time to write my opinion.I would also like to ask forgiveness for my bad English, I hope that despite my mistakes you can understand this text.In chapter 1 we have the most basic articles (or recipes): making a web server, simple routing, serving static files, caching, performance and a little about security. It's a good introduction for the rest of the book.Chapter 2 goes far away with HTTP communications: managing POST data, file uploads and downloads (with resume), and using Node as an HTTP client. All focused on web development. Nice.Chapter 3 is a good introduction before starting to talk about databases: JSON (and JSONP), XML and Ajax. This chapter finishes with a very interesting example about fetching trending tweets.Chapter 4 deals with databases. It's a very complete chapter that shows the use of multiple databases: from the typical MySQL to the most modern MongoDB, CouchDB and Redis, explaining the differences between them.After databases, chapter 5 talks about one of the most interesting HTML5 features: WebSockets. Starts by creating a WebSocket server with its corresponding client, to continue with socket.io, allowing WebSocket like experience to older browsers. The chapter ends with a widget example that provides a constantly update total of all users currently on site.Chapter 6 is more than just an introduction to web development with Express. It begins by explaining how to start developing your application with Express (scaffolding, defining environments), and continue with more advanced tasks like dynamic routing, templating systems (Jade, EJS), CSS engines (Stylus, LESS), and session management. Finally, shows us a not so simple application with Express, jade, stylus and mongosking.Chapter 7 discusses security. It's a very interesting chapter, because there aren't many serious articles online about Node's security and it is something vital before taking your application to production.You can find recipes about implementing several types of authentication: basic, digest, password encryption (MD5, SHA1, and more), and setting up an HTTPS server (with core Node and Express). Also includes recipes for preventing some types of vulnerabilities: CSRF and XSS.In chapter 8 we learn Node's capabilities beyond simply serving web pages: send emails (with and without attachments), send SMS and making automated phone calls (wow!), communication using TCP, making an SMTP server for sending and receive emails, and using virtual hosting for your apps (with and without Express).Chapter 9 will be one of the favourites for those who don't know the JavaScript modular and prototypical patterns. Maybe they should start the book for this chapter. The first recipe creates a test-driven module API whith core Node and then does the same using the should.js third-party module. The following recipe creates a functional module from the previous tests, then refactor this module from functional to prototypical (perfect!). The next recipe shows us how to extend to other modules: first tests are created and then implements the functionality (TDD with Node... awesome). Also integrates our module with EventEmitter, very useful for your own modules. Finally, after creating the module, shows how to share it with everyone through npm. A very complete chapter, I like it.Finally, chapter 10 deals with issues taking live your Node application, sice compress and upload to install and start the Node process. Again, a must read chapter with tons of unvaluable Linux commands.My conclusion: I think it's not a book for beginners. It's true that sometimes talks about basic issues, but it's an excuse for quickly get into more complex issues. This is good for me, a developer with experience on some programming languages like C, Java, PHP and JavaScript, but for newbies I think you should first read a good JavaScript and general web development book.There isn't a book with many pages, but each one contains much useful information for further research on your own. I have the impression that it's one of those books that require more than one reading.David Mark Clements does not waste time with long introductions trying to make reading more enjoyable, he goes straight to the point and from page 1 you will be writing code and practicing with Node.I liked it, I was surprised by the quantity and quality of code and I think it's a book that will go with me during a few months.
Amazon Verified review Amazon
Hasan Yasin Öztürk Oct 07, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
There are recipe books that just give you which ingredients to prepare, how to mix and cook them in a step by step fashion. There is also a different kind of books that give you a deeper idea about the ingredients chosen, why you are putting what, which pepper brings what kind of after taste, how cooking time and intensity of heat applied effects the taste. This book is one of the latter. It does not just gives a list of things to do to achieve specific results; but it takes the correct path and explains whys.The book covers topics from building your first web server to sending messages over SMS protocol. It has a complete section on Express, a popular framework which I personally don't prefer using; but know that many developers do. Connecting to and working with MySQL, MongoDB, and CouchDB are also some of the other topics that are covered.IMHO, first six chapters (Web Server, HTTP, Data Serialization, Databases, AJAX/Web Sockets) are the most useful ones for the people who are stepping into developing on Node. The last four chapters (Security, Network, Developing Node Modules, Deployment) are more for the people who have already an understanding of the system and have already been developing on Node.In last chapters there are things that, I believe, everybody would love finding in the book, such as deployment and building a server with automatic crash recovery. These chapters include system configuration and shell scripts. These are the things that will help you have a complete system, which many Node developers really need.Another interesting chapter is on building an SMTP server which will provide a lot of insights for both the beginner and developers who are not very confident with their knowledge of protocols and network systems.The language of the text is clear, simple, understandable. Some technical books have a problem of pushing it to look cool/funny by making awful jokes or extending the text unnecessarily with things that are out of the topic. This one is really mature and professionally written. Easy and fun to read without feeling awkward and having "huh?"s frequently.I wish we had more of the last sections than a section on things like Express Framework. I know 90% will disagree with me and that is probably why author did it this way; but I think those last/advanced sections are unique to the book and things covered are very hard to find online written as clearly and complete. The section on Express is pretty detailed, very complete and long (40+ pages) and it covers everything from css engines to profiling and many will love this; but later sections are much more useful for both newbies and advanced developers since they are more general and about more advanced topics.I recommend the book to everybody from beginners to active members of the Node community.
Amazon Verified review Amazon
sunil Nov 09, 2014
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is nice book with good examples
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.