How to Add a Package to Your Node Instance for Developing a MongoDB Web Services

Smartphone users are increasingly seeking all sorts of information through apps installed in their smartphone. This is why today’s world is a collaboration of social applications. Hence, it is necessary to have an easy to develop and install app along with its backend.

A number of companies depend on a stack by using advanced technologies like Node.js, MongoDB and Express. This specific stack is a very popular for mobile apps because the format of native data is JSON. JSON is easily parsed by applications through Cocoa’s NSJSONSerialization or other parsers that are comparable.

It is not easy without proper education. You have to know the way of adding package to your node instance for this purpose.

Objective of This Tutorial:

Reading this tutorial will be your medium to get yourself educated about the possible ways of setting up a Node.js development environment leveraging technologies like Express to help you add a package to your node instance to make sure you can develop a MongoDB web service that exposes a MongoDB database through a REST API.

Beginning:

Make sure you have OS X Mountain Lion or Mavericks and Xcode with its full range of command line tools preinstalled.

The First Step:

You need to install Homebrew. It manages Unix tools on Macintosh operating system X. It was built on top of technologies like Ruby on Rails and Git. It is extremely flexible and easy to customize. You just need to execute a command given below for the purpose of installing Homebrew:

ruby -e “$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)”

Skip to the next step if you already have it installed. Once Homebrews gets installed, execute the following command in terminal to have the most updated homebrews package list:

brew update

Now you should initiate the installation of MongoDB with a command given below:

brew install MongoDB

At this crucial step, you are advised to carefully notice the address to the directory where MongoDB gets installed as you will require this address to be able to launch the MongoDB service.

Now you should immediately download the Node.js installer run it right away for testing purpose.

Go back to the terminal and execute the following command:

Node

This will put you in Node.js interactive environment to help you perfectly execute JavaScript expressions.

Execute the following command at the command prompt:

console.log(“Hello World”);

Now following will be the output of your command

Hello World
undefined

As far as console.log is concerned, it is an equivalent of NSLog. The output stream of console.log is very complex as compared to the output stream of NSLog.

Remember, among other stream possibly expected by you from other advanced loggers like CocoaLumberjack, has console.info console.assert console.error

Talking about the undefined value written to the output is actually the return value of console.log that does not have any return value. As for Node.js, it always displays the value of every single expression. And it does not matter whether the return value is defined or undefined.

Executing a Node.js Script

Interactive environment for Node.js development is useful for playing around and also to debug your JavaScript expressions. However, you will utilize script files to get the actual task done. It is like an iOS including Main.m as its starting point. As far as the default entry for Node.js is concerned, it is index.js. Unlike Objective-C, it does not have any main function. Therefore, the evaluation process of index.js is conducted from top to bottom.

Now you need to press Control+C buttons from your keyboard to exit the shell of Node.js and execute a command given below with the objective of creating a new folder for holding your scripts.

mkdir ~/Documents/NodeTutorial

Now it is time for you to execute another command given below to be able to navigate this new folder for the purpose of creating a new script file in your default editor.

cd ~/Documents/NodeTutorial/; edit index.js

Also remember to add this code to index.js

console.log(“Hello World.”);

Now you should save your full work and get back to terminal and execute node index.js command to see your entire script running. As far as the output is concerned, it is should be again “Hello world”. You can also give a shot to node . For running your script. As for reason, it searches for index.js by default.

The next section of this tutorial is related to Node.js Packages for forming a much needed foundation of a new website server.

Node.js Packages

Node.js applications are generally divided into packages. These packages are the frameworks in Node.js environment. It provides a number of basic as well as powerful packages. Node.js development community generally provides more than 50,000 public packages. However, if you don’t get what exactly you need then you can easily develop the one you need and best caters to your requirements.

Coming back to point, try to replace the content of index.js with the code given below:

//1
var http = require(‘http’);
//2
http.createServer(function(req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/html’});
res.end(“<html><body><h1>Hello World</h1></body></html>”);
}).listen(3000);

console.log(‘Server running on port 3000.’);
Now let’s see the possible output:
require helps import all modules into the existing file. In this way, in this scenario, HTTP libraries are being imported by you.
Here you are creating a web service capable of responding to easy/simple HTTP requests. This is done by sending a 200 response. Writing he page content into the response also plays an important role in this whole process.
This is where Node.js displays its true strength as a runtime environment. And this strength of Node.js is actually event driven model. it is specifically designed around the concept of callbacks called asynchronously. In the example provided above, you are listening on port 3000 for HTTP requests that are incoming. When you get a request, the script executed by you calls function (req, res)(…) and the caller gets the response.
Now you need save the file and get back to terminal for executing a command mentioned below:
node index.js
Executing the command mentioned above will show you the console output.
The next step by you should be to open your favorite browser and navigate to http://localhost:3000. Now you will definitely see Node.js presenting you your “Hello World” page on your screen.
It simply means that your script is still in action and is waiting for http request on port 3000. Press CTRL+C to kill your Node.js instance.

Node JS Web Development Company

Use of External Modules of Node:
The previous section was about using Node.js modules. There are some third party modules also. You will surely need these third party modules to be able to provide routing middleware for your system.
All of these external modules are also imported into the file using the require function. These external modules have to download separately. Once downloaded, these external modules can be made available to your Node instance.
Node.js generally makes use of Node Packages Modules, for downloading and installation purpose, you need to use maintenance support services to maintain package dependencies. Knowledge about Cocoapods and Ruby Gems makes the whole process very easy and you will feel familiar with Node Packages Modules. Remember, your Node.js application makes use of package.json responsible for defining the configuration and dependencies of Node Packages Modules.
Use of Express

It is a popular Node.js module commonly used as a routing middleware. You specifically need this separate package to be able to develop a MogoDB web service that exposes a MongoDB database through a REST API for the following reasons:

If you have used only the HTTP module by itself then you will have to parse the location of every request separately to be able to figure the kind of content to be served up to the caller. And this will become a big problem.

Using Express, It is very easy to define routes and chains related to callbacks for every request. In addition to it, express also makes it very easy to ensure different callbacks that are based on the HTTP verbs.
Just a Look at HTTP Verbs

There is a method-or verb- value of HTTP requests. Its default value is GET for fetching data like website’s pages in your favorite browser. Talking about POST? It is also for the purpose of uploading data such as submission of web forms. As for web API, POST is usually utilized with the objective of adding data. POST can also be utilized for remote procedure call-type end-points.
It time for PUT that is different as compared to POST in that. Generally, it is utilized for replacing existing data. Honestly, both PUT and POST are utilized similarly. The main purpose of using PUT and POST is to provide entities in the request body likely to be placed into a backend datastore. But what is sued for removing items from your backend store? DELETE answers this question perfectly as it is used for this purpose.
Actually, POST, GET, PUT and DELETE are Hypertext Transfer Protocol implementations of CRUDE model followed. Here, CRIDE stands for Create, Read, Update and Delete

The Process of Adding to Node Instance:
For this purpose, you should execute the command given below in terminal:
edit package.json
This is for the purpose of creating a new package.json for containing your package’s configuration and dependencies.
Now you should ensure the addition of following code to package.json:
{
“name”: “mongo-server”,
“version”: “0.0.1”,
“private”:
true
,
“dependencies”: {
“express”: “3.3.4”
}
}
This particular file used for the objective of defining some metadata such as the name of project, version, scripts and package dependencies etc. Read below to know the meaning of every line:

  • Name is actually the name of project.
  • Version is the current version of the project.
  • Private makes sure that the project does not get published publicly accidently especially if it is set to true by you.
  • Coming to dependencies, it is the list of Node.js modules used by your application.

These dependencies normally take the form of key/value pairs that are related to module names and versions used by your application. The list of dependencies has version 3.3.4 of Express. Moreover, if you are planning to instruct Node.js to utilize the latest version of a package then using wildcard”*” is the best idea.
Now you should save the file and execute the command give below in terminal:
npm install
And you will now see the output on your screen.
Install downloads and plays an important part in the process of installing dependencies mentioned in package.json-” and your dependencies™ dependencies! This is done into a folder named mode-modules. Install makes sure that these dependencies are available to your application.
Remember, once npm gets completed, you are free to use express in your application.
Now you should find the line given below in index.js:
var http = require(‘http’);
Now you should try to add the require call for Express, as shown below:
var http = require(‘http’),
express = require(‘express’);
This will import the Express package and make sure it is stored in a variable named express.

Now make sure you add the following code to index.js immediately after the section you successfully added above:
var app = express();
app.set(‘port’, process.env.PORT || 3000);

This will create an Express app. As for its port, it will be set to 3000 by default. Creating an environment variable named port can help you overwrite this default. Such a customization is extremely useful while using Node.js as a development tool. It is specifically helpful when you have got more than one apps listening on a number of ports.

Now you simply need to add the code lines given below to index.js under the section added by you above.

app.get(‘/’, (req, res) {
res.send(“<html><body><h1>Hello World</h1></body></html>”);

});
This will create a route handler. It is a name related to chain for the purpose of request handlers for a given URL. Express matches all sorts of paths specified in the request and plays its due role in the process of executing the callback appropriately.
Now this callback commands Express to match the root “/” and also send back the given HTML in reply. As for send, it formats a lot of response headers for you. These response headers are like content-type and the status code to help you focus on writing high quality code instead.
At last, you are advised to replace the current http.createServer(…)down to and including the console.leg command in the code given below:
http.createServer(app).listen(app.get(‘port’), function(){
console.log(‘Express server listening on port ‘ + app.get(‘port’));
});

Without a doubt, it is slightly more compact as compared to the app implements the function (req, res) callback separately instead of including in the line at create server call.Express adds this metadata automatically to the response. This whole thing does not end here only as in this way, you have managed to add a completion handler callback which is also called once the port is open and ready to receive requests. Now your application has to wait for the port to get ready before logging the “Listening” message to the console.

Do you want to review? Now index.js should now look as given below:

http = require(‘http’),
express = require(‘express’);
var app = express();
app.set(‘port’, process.env.PORT || 3000);
app.get(‘/’, function (req, res) {
res.send(“<html><body><h1>Hello World</h1></body></html>”);

});
http.createServer(app).listen(app.get(‘port’), function (){
console.log(‘Express server listening on port ‘ + app.get(‘port’));
});

Now you need to save the file and execute another command given below:

node index.js

Now get back to your browser and reload http://localhost:3000 with the objective of making sure your “Hello World” page still loads. It does not look changed at all.

Now you should see it from another perspective to know what is going on under the hood. This is why you should create another instance of terminal and execute the command given below:

curl -v http://localhost:3000

Now you should get accurate output on your screen. Curl plays its role in the process of spiting the response headers back and also content for your HTTP request to help you display the raw details of everything being served up. Remember, X-Powered-By : Express header; Express adds this entire metadata automatically to entire response.

Final Thoughts:

Hopefully this much education will help you add a package to your node instance needed for serving up the content for express and advanced routing to be able to develop MongoDB web service that exposes a MongoDB database through a REST API using Maintenance support services.

Recent Posts

Categories

Tags