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
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (9 Ratings)
Paperback Jul 2012 342 pages 1st Edition
eBook
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon David Mark Clements
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (9 Ratings)
Paperback Jul 2012 342 pages 1st Edition
eBook
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

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 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 : 9781849517188
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 : Jul 25, 2012
Length: 342 pages
Edition : 1st
Language : English
ISBN-13 : 9781849517188
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 $ 152.97
Node Web Development - Second Edition
$48.99
Node Cookbook
$48.99
Mastering Node.js
$54.99
Total $ 152.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

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.