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
Learning Node.js for .NET  Developers
Learning Node.js for .NET  Developers

Learning Node.js for .NET Developers: Build server side applications with Node.js

eBook
€8.99 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

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

Learning Node.js for .NET Developers

Chapter 1. Why Node.js?

Node.js is still relatively new compared to platforms such as .NET and Java, but has become very popular in a short time, and has even started influencing these platforms. This is thanks to its distinctive programming model, extensive ecosystem, and powerful tooling.

These factors make Node.js a compelling alternative to other platforms. They can also make it intimidating. Its distinctive programming model may seem quite alien compared to other platforms. The sheer range of available libraries and tools can be bewildering.

This book will guide you through Node.js so you can start using it in your applications. It will help you to understand Node.js, navigate its ecosystem, and leverage your existing development skills in this new environment.

In this chapter, we will cover the following topics:

  • Introducing the Node.js platform
  • Seeing how its execution model works
  • Exploring the Node.js ecosystem
  • Looking at JavaScript as a language choice
  • Considering the range of use cases for Node.js

What is Node.js?

Node.js consists of a JavaScript engine together with low-level APIs for core server-side functionality. The execution engine is the same V8 engine developed for the Chrome web browser. Node.js takes this engine and embeds it in a standalone application that can run JavaScript outside the browser.

In Node.js, the standard APIs found in browsers to support client-side web development, such as the Document Object Model (DOM) and XMLHttpRequest, are not present. Instead, there are APIs to support general-purpose application development. These core APIs cover low-level functionality such as the following:

  • Networking and security
  • Accessing the file system
  • Defining and requiring modules
  • Raising and consuming events
  • Handling binary data streams
  • Compression
  • UTF-8 support
  • Retrieving basic information about the OS
  • Managing child processes

Some of these APIs may already be familiar from developing client-side JavaScript. For example, the Timers API exposes the familiar setTimeout and setInterval functions.

Node.js also provides several tools to help with the development process. These include console logging, debugging, a Read-Eval-Print Loop (REPL) (or interactive console), and basic assertions for testing.

Understanding the Node.js execution model

The execution model of Node.js follows that of JavaScript in the browser. It is quite different from that of most general-purpose programming platforms.

Stated formally, Node.js has a single-threaded, non-blocking, event-driven execution model. We will define each of these terms in this section.

Non-blocking

Put simply, Node.js recognizes that many programmes spend most of their time waiting for other things to happen, for example, slow I/O operations such as disk access and network requests.

Node.js addresses this by making these operations non-blocking. This means that program execution can continue while they happen. For example, the filesystem API's stat function for retrieving statistics about a file may be called as follows:

fs.stat('/hello/world', function (error, stats) {
  console.log('File last updated at: ' + stats.mtime);
});

Two arguments are passed to the fs.stat function: the name of the file that we are interested in, and a callback function. The fs.stat call returns immediately, returning control of execution to the current thread but not returning a value. If there are further commands following the fs.stat call, these will then be executed. Otherwise, the thread is released to perform other work. The callback function is invoked (that is 'called back') only after the runtime has finished communicating with the filesystem. The result of the filesystem operation is passed into the callback function.

This non-blocking approach is also called asynchronous programming. Other platforms support this (for example, C#'s async/await keywords and .NET's Task Parallel Library). However, it is baked in to Node.js in a way that makes it simple and natural to use. Asynchronous API methods are all called in the same way as fs.stat. They all take a callback function that gets passed error and result arguments.

Event-driven

The event-driven nature of Node.js describes how operations are scheduled. In typical procedural environments, a program has an entry point that executes a set of commands until completion, or enters a loop and performs some processing on each iteration.

Node.js has a built-in event loop, which isn't exposed to the developer. It is the job of the event loop to decide which piece of code to execute next. Typically, this will be a callback function that is ready to run in response to some other event. For example, a filesystem operation may have completed, a timeout may have expired, or a new network request may have arrived.

This built-in event loop simplifies asynchronous programming by providing a consistent approach and avoiding the need for applications to manage their own scheduling.

Single-threaded

The single-threaded nature of Node.js simply means that there is only one thread of execution in each process. Also, each piece of code is guaranteed to run to completion without being interrupted by other operations. This greatly simplifies development and makes programs easier to reason about. It removes the possibility for a range of concurrency issues. For example, it is not necessary to synchronize/lock access to shared in-process state as it is in Java or .NET. A process can't deadlock itself or create race conditions within its own code. Single-threaded programming is only feasible if the thread never gets blocked waiting for long-running work to complete. Thus, this simplified programming model is made possible by the non-blocking nature of Node.js.

Introducing the Node.js ecosystem

The built-in Node.js APIs provide a low-level core for creating applications. Applications typically only use a small number of these APIs directly. They often use third-party library modules that provide higher-level abstractions for application development.

Node.js has its own package manager, npm. This is similar to .NET's NuGet or the package management aspects of Java's Maven. Applications specify their dependencies in a simple JSON file.

The npm registry provides a central repository for packages. This registry has grown rapidly and is already much larger (in terms of number of available packages) than the corresponding repositories for other platforms (see http://www.modulecounts.com/). There are hundreds of thousands of packages available, providing a vast array of functionality.

The npm command line tool can be used to download packages and install new ones. Library dependencies are installed locally to each application. Some packages provide command-line tools, which may be installed globally rather than under a specific project.

Many frameworks available on npm are split into a small extensible core and a number of composable modules. This approach makes it easy to understand the libraries on which your application depends, avoiding the need to reason about complex heavyweight frameworks.

The consistency of calling non-blocking (asynchronous) API methods in Node.js carries through to its third-party libraries. This consistency makes it easy to build applications that are asynchronous throughout.

Why JavaScript?

JavaScript is a language that can seem unintuitive compared to other popular object-oriented (OO) languages. It also has a number of quirks and flaws that have drawn criticism (and occasional ridicule). It might then seem a surprising choice of language for a new programming platform. This section discusses the factors that make JavaScript a more appealing choice.

A clear canvas

The size and complexity of JavaScript is part of its appeal. The core language itself, which doesn't include APIs such as the DOM, is small and simple. This makes it easy for Node.js to establish its own styles and conventions.

The new APIs provided by Node.js and the consistent approach to asynchronous programming wouldn't be possible in a more complex language with a larger pre-existing standard class library.

Functional nature

JavaScript was first built as a programming language for client-side functionality in the browser. This might not make it an obvious choice for general-purpose programming.

In fact, these two use cases do have something important in common. User interface code is naturally event-driven (for example, binding event handlers to button clicks). Node.js makes this a virtue by applying an event-driven approach to general-purpose programming.

JavaScript supports functions as first-class objects. This means it's easy to create functions dynamically and pass around references to them. This fits in well with the asynchronous, non-blocking approach of Node.js. In particular, it's easy to expose and use APIs based around callback functions.

A bright future

JavaScript has received a lot of attention in the last several years as it has become more widely used for providing rich functionality on the Web. Browser vendors have put a huge amount of engineering effort into improving the performance of JavaScript. Node.js benefits from this directly via its use of Chrome's V8 engine.

The JavaScript language itself is undergoing some major changes for the better. The ECMAScript 2015 standard (previously known as ES6) represents the most significant revision of the language in its history. It introduces features that make the language more intuitive and less verbose. It also addresses flaws that JavaScript has been criticized for in the past, removing gotchas and making programs easier to reason about.

When to use Node.js

As discussed earlier in this chapter, Node.js recognizes that I/O is a bottleneck for many applications. On most programming platforms, threads will waste time blocking on I/O operations. There are approaches developers can take to avoid this, but these all involve adding some complexity to their code. In Node.js, the platform itself provides a completely natural approach.

Writing web applications

The flagship use case for Node.js is building web applications. These are inherently event-driven as most or all processing takes place in response to HTTP requests. Also, many websites do little computational heavy-lifting of their own. They tend to perform a lot of I/O operations:

  • Streaming requests from the client
  • Talking to a database, locally or over the network
  • Pulling in data from remote APIs over the network
  • Reading files from disk to send back to the client

These factors make I/O operations a likely bottleneck for web applications. The non-blocking programming model of Node.js allows web applications to make the most of a single thread. As soon as any of these I/O operations starts, the thread is immediately free to pick up and start processing another request. Processing of each request continues via asynchronous callbacks when I/O operations complete. The processing thread is only kicking off and linking together these operations, never waiting for them to complete. This allows Node.js to handle a much higher rate of requests per thread than other platforms. You can also still make use of multiple threads (for example, on multi-core CPUs) by simply running multiple instances of the Node.js process.

Identifying other use cases

There are of course some applications that don't perform much I/O and are more likely to be CPU bound. Node.js would be less suitable for computationally-intensive applications. Programs that do a lot of processing of in-memory data are less concerned about I/O.

Web applications are not the only I/O-heavy applications though. Other classes of program that could be a good candidate for Node.js include the following:

  • Tools that manipulate large amounts of data on disk
  • Supervisor programs coordinating other software or hardware
  • Non-browser GUI applications that need to respond to user input

Node.js is especially suitable for glue applications that pull together functionality from other remote services. The increasing popularity of microservices as an architectural pattern makes this kind of application more common.

Why now?

Node.js has been around for several years, but now is the perfect time to start using it if you haven't already.

The release of Node.js v4 towards the end of 2015 consolidated the project's governance model and heralds Node.js coming to maturity. It also allows the project to keep more up to date with the V8 engine. This means that Node.js can benefit more directly from ongoing development on V8. For example, security and performance improvements to V8 will now make their way into Node.js much sooner.

As discussed earlier in this chapter, the release of the ECMAScript 2015 standard makes JavaScript a much more appealing language. It pulls in useful features from other popular OO languages and resolves a number of long-standing flaws in JavaScript.

Meanwhile, the ecosystem of third party libraries and tools around Node.js and JavaScript continues to grow. Node.js is treated as a first-class citizen by major hosting platforms. Companies such as Google and Microsoft are also throwing their weight behind JavaScript and related technologies.

Summary

In this chapter, we have understood Node.js and its distinctive execution model, explored the growing ecosystem around Node.js and JavaScript, seen the reasons for JavaScript as a language choice, and described the kinds of application that can benefit from Node.js.

Now that you know how Node.js works and when to use it, it's time to dive in and get our first Node.js application up and running.

Left arrow icon Right arrow icon

Key benefits

  • Learn the concepts of Node.js to gain a high-level understanding of the Node.js execution model
  • Build an interactive web application with MongoDB and Redis and create your own JavaScript modules that work both on the client side and server side
  • Familiarize yourself with the new features of Node.js and JavaScript with this exclusive step-by-step guide

Description

Node.js is an open source, cross-platform runtime environment that allows you to use JavaScript to develop server-side web applications. This short guide will help you develop applications using JavaScript and Node.js, leverage your existing programming skills from .NET or Java, and make the most of these other platforms through understanding the Node.js programming model. You will learn how to build web applications and APIs in Node, discover packages in the Node.js ecosystem, test and deploy your Node.js code, and more. Finally, you will discover how to integrate Node.js and .NET code.

Who is this book for?

This book is for developers who want to learn JavaScript and Node.js. Previous experience with programming is desired, but no JavaScript or Node.js knowledge is required. The book focuses mostly on web development, such as networking, serving dynamic pages, and real-time client-server communication.

What you will learn

  • Understand which problems Node.js best solves
  • Write idiomatic JavaScript and Node.js code
  • Build web applications and command-line tools
  • Minimise complexity and efficiently solve difficult problems
  • Test and deploy Node.js applications
  • Work with persistent data
  • Implement real-time client-server applications
  • Integrate .NET and Node.js code
Estimated delivery fee Deliver to Latvia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 24, 2016
Length: 248 pages
Edition : 1st
Language : English
ISBN-13 : 9781785280092
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Latvia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Jun 24, 2016
Length: 248 pages
Edition : 1st
Language : English
ISBN-13 : 9781785280092
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 103.97
Reactive Programming for .NET Developers
€36.99
Learning Node.js for .NET  Developers
€24.99
JavaScript for .NET Developers
€41.99
Total 103.97 Stars icon
Banner background image

Table of Contents

15 Chapters
1. Why Node.js? Chevron down icon Chevron up icon
2. Getting Started with Node.js Chevron down icon Chevron up icon
3. A JavaScript Primer Chevron down icon Chevron up icon
4. Introducing Node.js Modules Chevron down icon Chevron up icon
5. Creating Dynamic Websites Chevron down icon Chevron up icon
6. Testing Node.js Applications Chevron down icon Chevron up icon
7. Setting up an Automated Build Chevron down icon Chevron up icon
8. Mastering Asynchronicity Chevron down icon Chevron up icon
9. Persisting Data Chevron down icon Chevron up icon
10. Creating Real-time Web Apps Chevron down icon Chevron up icon
11. Deploying Node.js Applications Chevron down icon Chevron up icon
12. Authentication in Node.js Chevron down icon Chevron up icon
13. Creating JavaScript Packages Chevron down icon Chevron up icon
14. Node.js and Beyond Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(2 Ratings)
5 star 0%
4 star 100%
3 star 0%
2 star 0%
1 star 0%
Gary A. Miller Jul 30, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Looks like it's covering all of the topics I thought it would.The one exception is Visual Studio. I wish it covered Node.js development using Visual Studio more thoroughly.
Amazon Verified review Amazon
Go Edmonton Oct 04, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Not sure about the "for .Net developers" was proper or not though.
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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela