Are the node js docs good

Creation of a Node.js and MongoDB web service

  • 17 minutes to read

This article has been machine translated.

Azure websites

Tejaswi Redkar

Download the code samples

The cloud is neutral for all languages. In the cloud, it shouldn't matter if the apps you are running are Node.js, ASP.NET, Java or PHP, because the cloud provides a ready-made infrastructure for them to run. The religion of the cloud is agility and agility allows you to implement new ideas quickly and sunset those that don't work in the market. In recent years, Node.js has gained popularity among a new class of developers who favor the asynchronous programming paradigm. Node.js is a JavaScript runtime engine for building client and server applications. It includes an asynchronous I / O framework that helps it handle thousands of simultaneous connections on a single thread with minimal CPU or memory overhead. It's a popular myth that Node.js is available as a web development framework; in fact, it is a single-threaded runtime engine for executing JavaScript code. It has a module-based architecture that allows any user to create and publish a module to handle specific tasks, such as web development or accessing a MongoDB database. The Express Template Engine is, for example, a web application framework that you can download as a module in Node.js. The core module of Node.js is based in C ++ on the Google V8 JavaScript engine, which was developed for the Chrome browser. Node.js is supported in the Microsoft Azure websites, and Microsoft also provides development tools and a native SDK for programming with Azure APIs. There is a special Developer Center Node.js in the Azure portal at bit.ly/1iupElQ.

In this article, I'll show you how to develop a RESTful web service in Node.js that accesses a MongoDB database in the cloud, and show you how to deploy it on Azure websites.

Node.js is based on an asynchronous development model, which means that every method call made requires a callback to receive the response. Although .NET developers traditionally prefer synchronous (request-response) method calls, asynchronous functions have always existed in the Microsoft .NET Framework. With the inclusion of the new async programming model in the .NET Framework, expect asynchronous applications over the web and mobile applications to become the norm. In asynchronous programming, the calling function subscribes to the callback event and provides a processing delegate with the response. The callback function is called when processing is complete. It's like e-mail versus making a phone call.

The following is a simple Node.js web server that returns a string that when called:

Note that the response function is called when an HTTP request event is triggered. The require function is used to load modules, similar to how namespaces are loaded from assemblies in the .NET Framework.

There has been a lot of discussion and religious arguments on ASP.NET versus Node.js, but I'm not going to touch the subject of this article. My approach has always been to use the best tool for the job and what is good for you to do your best.

Node.js request processing

As illustration 1 shows the Node.js module begins to handle a single thread for concurrent client connections. As the single thread is already initialized, there is no initialization overhead needed for processing any increase in requests because the thread quickly asynchronously delegates the request to a worker thread for processing.


Figure 1 Node.js request / response orchestration

When the HTTP incudes a long-running or I / O-intensive task, such as database access or a web service call request, it is running asynchronously non-blocking worker threads. Once the long-running process is complete, the worker threads return the results as a callback to the main thread. The main thread returns the result to the client. An ImporTant concept to understand here is that the receiving single thread can always receive requests and not stay busy with the processing, since the processing is delegated to the worker threads.

Node.js core components

Node.js consists of two main components:

Core / Kernel: The core of Node.js is written in C ++ on top of the Google V8 JavaScript engine. The core itself is singlethreaded and suitable for load balancing between CPUs. Node.js is open source and you can get the source code from github.com/joyent/node.

Modules: Modules are comparable to NuGet packages in the .NET Framework. Node.js Package Manager (NPM) is the tool for managing Node.js packages in your development environment. Modules create new processes or threads depending on the intensity of the I / O task. Popular modules include HTTP, MongoDB, Express (a web framework for the template), and Socket.IO. For a list of the most popular modules, please visit nodejsmodules.org.

Install and run Node.js locally

Before running a Node.js website in the cloud, I recommend trying out the platform comfortably locally. You can install and run Node.js on a Windows platform in just three steps:

  1. Downloading and installing Node.js: Node.js Windows Installer can be downloaded and installed from nodejs.org/#download. The installer installs the Node.js runtime and NPM.
  2. Create a simple server: To create an HTTP server in Node.js, open your favorite text editor, copy the code illustration 1and save the file as webserver.js. The code shown earlier creates a minimalist web server that listens on port 8080 and responds with the same string for every request.
  3. Run the HTTP server: Finally, to run the server, open the command prompt, navigate to the folder where you saved the webserver.js file, and type:
    > "C: \ Program Files \ nodejs \ node.exe" webserver.js
  4. This command starts the web server, and you can test it by navigating your browser to http: // localhost: 8080. This simple server should give you enough confidence to try Node.js as an option for web site development.

Node.js running on Azure websites

When I first used Node.js, I decided to avoid the command line as much as possible. Having lived my life in Visual Studio, I really appreciate the productivity that you can achieve using an IDE. Fortunately, Microsoft has invested in WebMatrix, a powerful tool for developing Node.js applications on Windows. The Visual Studio team also released the Node.js tools for Visual Studio (nodejstools.codeplex.com). For the remainder of this article, I'll be using WebMatrix as my primary development tool. From WebMatrix you can run NPM installation packages, publish websites to Azure and also locally. WebMatrix also installs IISNode for IIS Express, which can host the Node.js application on IIS. For more information about IISNode, visit github.com/tjanczuk/iisnode.

Before building a complete RESTful web service, I'll show you how to publish a simple web site to Azure from WebMatrix.

Create a new Azure website You can create a new website in Azure from the Azure portal as shown in Figure 2.


Figure 2 Create New Azure Website

The portal will create a new website with a unique name in the region you specify. The region is important for co-localizing your website, databases and other services in the same data center. Data that leaves a data center pays.

Create an express website Express is a web application framework for Node.js. It follows the Model-View-Controller (MVC) pattern and therefore you can create routes for building Node.js MVC web sites as well as RESTful web services. You can get express from expressjs.com.

If you love .NET development in Visual Studio, I recommend mastering WebMatrix Node.js to develop applications. WebMatrix 3 includes a useful ready-made Express template. Open it and click on new | Office templates. Under the Node.js category, select the Express website template, see Figure 3.

Enter a site name and click Next to install IISNode and the Express website template.


Figure 3 Express website template

The Node.js server I built earlier did not run like it does on Azure websites, since the infrastructure Azure websites depends on IIS for running websites. Therefore, in order to run a Node.js website, I need the integration between IIS and Node.js that IISNode provides.

Figure 4 illustrates the file structure created by the Express template and source code for server.js.


Figure 4 Express File Structure

Note that the Express and Routes modules get imported automatically. I will use these modules to create the REST services.

The site running locally Following my earlier recommendation, click Run on WebMatrix to test the website on the local computer. If the installation was successful, you should see the Express home page.

The Jade template engine is also installed as an express template. Jade is an HTML template engine and is used to create views generated from the Express framework. Jade is expressing what ASP.NET MVC Razor is for. Therefore the index.html contents of /views/index.jade and /routes/index.js are rendered. These routes are set up on lines 16, 17 and 30 of the server.js, see Figure 4. For more information on the Jade template engine, visit Jade-lang.com.

Publish the website to Azure Now that you've built a Node.js website in Express locally, we're going to publish it on Azure. Click the publish button in WebMatrix to start the process. Import the publishing profile for your web site and follow the Publishing Wizard as in Figure 5.


Figure 5 Publish Microsoft Azure

If all goes well, your web site's WebMatrix will load into Internet Explorer.

The URL in the browser should be the Azure website where you published the website. This is a good illustration of how easy it is to develop and deploy Node.js websites and web services on Azure. Now I'll take a moment to look at MongoDB. I'll come back to Node.js later, creating web services.

MongoDB overview

MongoDB is an open-source, scalable, high-performance, document-oriented database, most of the infrastructure functions of relational databases, e. B. Includes replication, splitter, indexing and failover. MongoDB also offers auto-splitter and has built-in card-reduction processing capabilities that are not offered by most relational databases today. Relational databases were developed at a time when storage systems were expensive. Storing data in a relational format allows developers to optimize storage space without having to query data quickly. In today's world, memory is cheap compared to calculate the cost. In the cloud, storage prices continue to fall. As a result, storing and retrieving data in relational format is expensive compared to storing it in the cloud. The demand for continuous data delivery is on the rise, with more applications expecting real-time data from your data store. MongoDB allows you to store objects and documents without breaking them into relational components. This reduces the processing load on the application as well as the database.

MongoDB is not recommended for applications that require deep object relationships as it is not intended to link, manage, and retrieve object and data relationships like relational databases. If your application requires deep relationships and SQL for retrieval, use a relational database. If your application requires fast object storage and retrieval, use MongoDB. As I suggested earlier, use the best tool for the job.

Deployment of MongoDB in Azure

MongoDB is available as an add-on in the Azure store and you can install a sandbox version for free. Log in to the Azure portal and reinstall MongoDB (MongoLab) from | Shop | Add-on menu, as in the Figure 6.


Figure 6 MongoDB accessories from MongoLab

On the Personalize Add-On page, select the sandbox version, and be sure to install the MongoDB instance in the same region as your web site as in Figure 7.


Figure 7 configure MongoDB

Once the installation is complete, navigate to the add-ons page and save the connection string for the installed database, as shown in Figure 8. You will be using the connection string to connect from your Node.js web service.


Figure 8 Connection String for the Installed Database

MongoDB is now running on Azure. MongoLab (by ObjectLabs Corp.) has its own dedicated management portal which you can view by clicking the Manage Your Add-ons link.

You have now run a MongoDB database in the cloud and you have created a blank Node.js template. To exit the application, you need to populate the MongoDB database and create the web services that will pull data from that database. This is the standard software development in the cloud.

Installation Node.js Requirements for MongoDB connectivity

JSON is a prime citizen in MongoDB and therefore complements Node.js. Because the web service is establishing MongoDB, I need to install the latest Node.js driver for MongoDB from the NPM gallery (see Figure 9).


Figure 9 Node.js driver for MongoDB

The MongoDB connection information is stored in a configuration file. Nconf module you can read configuration information from files (see Figure 10).


Figure 10 Nconf module

Once the Mongodb and Nconf modules are installed, you have completed the prerequisites for setting up a Node.js and MongoDB development environment.

Create the REST web service signatures

To create a REST web service, first define dependencies and routes in server.js:

Then you define the REST functions in the /routes/pkgs.js- file because in the previous code, you delegate the function to the Pkgs module handling. Create routes in the folder a file called pkgs.js that defines the web service as in Figure 11.

Figure 11 REST process signatures

To test the basic functioning of the operations, simply create function skeletons to return static data. You can add access code to the database later. Server.js define the route methods that correspond to the module methods you just created:

If you are familiar with the ASP.NET Web API, you will quickly understand these routes and how they are mapped to the appropriate implementation class. With the route declaration and assignment, each request to / pkgs is routed to one of the functions in pkgs.js. With the web service process signatures and definitions in place, you can test that the routes are working properly by running the website locally, as well as Azure. The URLs to test are: http: // [Web-Site-Url] / Pkgs, http: // [Web-Site-URL] / Pkgs / remote, and http: // [Web-Site-Url] / Pkgs / 1 . If these urls return the expected values, then the routes are working fine and you can with the MongoDB integration.

Implementation of the REST web service measures

Now you need to implement the web services operations to connect MongoDB and get the data. There are four steps to achieve this:

  1. Create a config.json file, and store the MongoDB connection string in it.
  2. Initialize the MongoDB client.
  3. Populating MongoDB with sample data. In this step the function makes an HTTP GET to call http: //storage.appsforazure.com/appsforazureobjectstest/servicepackages.json and stores the retrieved data in the MongoDB instance.
  4. Implementation of the data access functions for the retrieval and storage of data in MongoDB.

Create the config.json file the config.json file which is similar to a .NET "app.config" but in JSON format stores the configuration information. Add the following name / value pair to the new file:

The value is the MongoDB connection string that you previously saved from the Azure portal.

In pkgs.js you have to import the Nconf module to read the configuration values:

The ConnectionString variable can then be used by the functions to connect to the MongoDB database. Note that the ConnectionString is declared as a global variable in pkgs.js so that it can access all functions.

Initializing the MongoDB client: To initialize a connection to the MongoDB database, you have to import the Mongodb module and call the Connect method, see Figure 12.

Figure 12 Connect to MongoDB Database

If the connection is successful, set the db variable in Figure 12 contains the database connection object. The db.collection function tries to connect to a collection named pkgs.If Pkgs does not exist, a new one is created by calling the PopulateDB function. In a real application, you would have to do this because the collection would actually arise before you run the application. (A listing in MongoDB is a grouping of posts on this topic, analogous to a database table in a relational database system.)

Fill MongoDB with sample data For this article, I have sample data available as a collection of software packages from dynamicdeploy.com. In the PopulateDB function, I upload this collection in JSON format from http://storage.appsforazure.com/appsforazureobjectstest/servicepackages.json, see Figure 13.

Figure 13 Populating the database

Note that JSON is a first class citizen in Node.js, so you don't need to import a module to parse the JSON objects. The collection.insert function inserts the entire JSON document (Var Pkgs) into the MongoDB collection. MongoDB determines the schema of objects at runtime and makes smart decisions about storing them. In a relational database, you would need to define the schema of the table before storing any data in it. A collection gives you the flexibility to change the schema at runtime, simply by changing the properties of the JSON objects. If the object properties change, MongoDB applies those changes to the schema before saving the object. This is useful for creating applications, such as social and Internet of Things RSS feeds, that change dynamically with changes in data types.

Implementation of the data access functions Finally you need to implement the data access functions for the HTTP GET, POST and PUT functions declared earlier. The HTTP GET function is mapped to the FindById and FindAll functions in the service, as in Figure 14.

Figure 14 the search functions

The FindById function gets an object by its ID, while the FindAll function gets all objects. Functions collection.findOne collection.find and retrieve the results of these operations from MongoDB, respectively. As well Figure 15 shows the AddPkg method associated with an HTTP POST and the UpdatePkg method associated with an HTTP PUT.

Figure 15 Adding and Updating Features

If you've followed the article so far, you should be able to implement a delete function on your own. I'll leave this as an exercise for you. Save and run the website locally first and then publish to Azure websites to test every REST functionality. The full source code for the REST web service and website is at github.com/dynamicdeploy/appsforazure.

Once you have the end-to-end application running, you can scale your MongoDB infrastructure (or service) depending on the user load. As this article shows, you don't need to deploy large-scale Node.js and MongoDB websites on Azure. The skeleton that I provided in the associated source code will help you get started creating web services and websites in Node.js on Azure websites.

Summary

The purpose of this article was to get you comfortable building web services in Node.js on Azure websites. Node.js and MongoDB complement each other and because both are available as Everything as a Service (PaaS), there is no upfront infrastructure, the cost of building a complete website and scaling it dynamically. As a developer, you can focus on creating and using web services right from the cloud in your mobile applications. Hence, I consider Azure PaaS web sites done right.

Tejaswi Redkaris an author and software developer. He currently works as the Director of Platform Strategy and Communities Application for Microsoft. His book, "Windows Azure Websites: Building Web Applications at a Rapid Pace" (Dynamic Deploy LLC, 2013), is the most comprehensive and best-selling on the subject. Redkar is also the creator of the Appsforazure Windows Storage app and dynamicdeploy.com, where he has first hand experience of running production applications in the cloud. You can reach him at [email protected] and follow him on Twitter at twitter.com/tejaswiredkar.

Thanks to the following technical experts for reviewing this article: Microsoft Azure the Product Management Team