node js on mac machine

Update Node and npm on mac OSX

How to completely remove Node and reinstall it

It might be a bit annoying to uninstall stuff. But sometimes you gotta do it.

To uninstall node completely from your machine:
brew uninstall --ignore-dependencies npm

This will handle the issue you may have with dependencies. If you have other modules like yarn or jhipster on your machine, they are dependent on node and uninstalling might not come easy.

To uninstall node in a more aggressive way:
rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/npm*

how to install node, npm (node package manager) on Mac OSX

It is rather simple. Just go to https://nodejs.org and download and follow the steps.

using mongodb with nodejs and angular js

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

This is a final part of the node angular and mongodb tutorial.

So far each part of the whole process has been shown by far. This is a part showing how the data would be pulled and shown to the angular based page.

Mind you, in this tutorial, the page was getting the list from the hard coded array and that is simply changed to the array that is read from mongodb. That part can be hooked to other datasources like MsSQL server or MySQL or anything.

Using MongoDB in Node JS

1. Create a folder named node-mongo

2. install mongodb and express packages there

sudo npm install express
sudo npm install mongodb

*I will have another tutorial showing how to use the package manager using package.json. But for now just install the packages like the one I showed above.

3. create server.js in node-mongo folder and add the following content in it


var express = require('express');
var app = express();

//connection string for mongo
var mongoPath = "mongodb://localhost:27017/nodemongo";
//require mongo and get the client.
var mongoClient = require('mongodb').MongoClient;

//a router for the home page. "/" being the home page
app.get("/", function(request, response){
    response.sendFile(__dirname + "/views/home.html");
});

//a router for listening to /listcountries 
app.get("/listcountries", function(request, response){

    // mongo connection comes from here
    mongoClient.connect(mongoPath, function(error, database){
        var result = {};
        
        //once connected, then get the row from mongo database. find() would list all
        if (error) {
            result.message = "Connection error";
            response.send(result);
        } else {
            var collection = database.collection("countries");
            collection.find().toArray((err, listOfCountries)=>{
                response.send({"list":listOfCountries});
            });
        }
    });    
});

app.listen(8080);
console.log("serving web on port 8080");

By now, most of the usages on this file would be easy to understand if you have followed the previous tutorials.

How to install mongo in the computer and how to add some collections to it and the like is beyond the scope of this tutorial and I assume you have already installed mongo on your system and have created a database and collection with it.

In the example above, I have used mongo database named nodemongo and collection countries

4. create a folder views in node-mongo

5. create a file home.html and add the following code in in it


<html>
<head><title>Countries</title></head>
<body ng-app="NodeMongoApp">
<h2>here you would unleash the science of listing countries</h2>
<div ng-controller="MongoController">
    <a href="#" ng-click="listCountries()">list countries</a>

    <ul ng-repeat="country in countries">
        {{country.name}}
    </ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
    var app = angular.module("NodeMongoApp", []);
    app.controller("MongoController", function($scope, $http){
        
        $scope.listCountries = function() {
            $http.get("/listcountries").success(function(countries){
                $scope.countries = countries.list;    
            });
        };
    });
</script>
</body>
</html>

That is it.

Now you will want to be in the node-mongo folder and issue

node server.js

and from your browser, go to http://localhost:8080

You can download the whole project here

using angular js with node js application example

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

Take a look on this tutorial and I will use the same setup with it

Follow until step 5 from the above example.

If you see the server.js, it will populate the hardcoded countries the template file countries.ejs file.

But this time, we dont need the ejs file at all, rather all what is needed from the node js server is to provide the json formatted response of the countries.

In the server.js file, add the following code


var express = require("express");
var app = express();

app.set("views", __dirname + '/views');

app.get("/", function(request, response){
   response.sendFile(__dirname + '/views/index.html'); 
});

app.get("/listcountries", function(request, response){
    var title = "List of Countries";
    var hardCodedCountries = [{"name":"America","population":300}, {"name":"Britain","population":53},{"name":"Canada","population":35},{"name": "Democratic Congo","population":67},{"name": "Ethiopia","population":90}, {"name":"Finland", "population":5}, {"name":"Gabon", "population": 2}];
    response.send(hardCodedCountries);
});

app.listen(8080);
console.log("Hit http://localhost:8080");

On this one, the view engine is removed and also the response.render is replaced by response.send

In short, the node has created an endpoint named /listcountries that would list countries and send that to the requester.

6. Now, the next task would be to update the page that would list the countries using angular

update the index.html file in views folder as follows


<html>
<head><title>Node with template</title></head>
<body ng-app="AngularNodeApp">
<div ng-controller="CountryController">
	<h2>Listing countries has never been easy</h2>
	<a href="#" ng-click="listCountries()">List Countries</a>

	<div>
	<ul ng-repeat="country in countries">
		<li>{{country.name}} | {{country.population}}</li>
	</ul>
	</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var app = angular.module("AngularNodeApp", []);
app.controller("CountryController", function($scope, $http){
	//get the list of countries
	$scope.listCountries = function() {
                //call the API to listcountries and get the list of countries as json response
		$http.get("/listcountries").success(function(countries_from_node){
                //assign countries variable that is accessed through $scope
		$scope.countries = countries_from_node;
		});
	};
});
</script>
</body>
</html>

Here it is clear that, the front and backend are separated in that the front end would act in its own by requesting what it needs from the backend only. As long as the node js is responding the list through its listcountries

Next: Using mongo db in the angular node js application

Using template engine in node js to render response values example

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

In this tutorial, the user input was accepted and processed, but the result was not sent to another html page that contains the result.

In real world application that is common task, say if you have a page listing the name of countries by reading them from data source, the returned page should populate the list of countries with probably other information which is well formatted with css and even some javascripts.

For this, the node has provided the templating engine.

What the template engine does is, it will put some placeholders for the variables that are sent from the server, process them and will finally output html file.

There are many template engines out there for node, I have used ejs since it is easy to use and has similarity with HTML and javascript.

Using template engine in node js to render html pages

1. create a directory node-template

2. move to that directory and issue the following command to install express in it

sudo npm install express

3. The above command would install express package in node_modules folder. This is the folder where all third party packages would be stored.

4. install ejs template engine

sudo npm install ejs

5. create server.js in node-template folder and add the following code in it


var express = require("express");
var app = express();

app.set("view engine", "ejs");
app.set("views", __dirname + '/views');

//router for the home page
app.get("/", function(request, response){
   //this doesn't need anything to be rendered so it is provided simple html file
   response.sendFile(__dirname + '/views/index.html'); 
});

//router for listcountries path
app.get("/listcountries", function(request, response){
    var title = "List of Countries";
    //instantiate the list of countries from hard coded array
    var hardCodedCountries = [{"name":"America","population":300}, {"name":"Britain","population":53},{"name":"Canada","population":35},{"name": "Democratic Congo","population":67},{"name": "Ethiopia","population":90}, {"name":"Finland", "population":5}, {"name":"Gabon", "population": 2}];
    response.render("countries", {'countries': hardCodedCountries, 'title': title});
});

app.listen(8080);
console.log("Hit http://localhost:8080");

From the above code, the part

app.set("view engine", "ejs");
app.set("views", __dirname + '/views');

Tells the node what template engine we are using and where the template pages are supposed to be residing. The __dirname is the current directory of the running script

Another point is, you see response.render that is where the ejs would be useful. It would take the countries list and iterate through them to display. The hardCodedCountries and title are computed values that are passed to the template file.

Further ejs syntax and usage can be seen here

6. Create file countries.ejs and add the following code in it.


<html>
<head><title>With template engine</title></head>
<body>
<h2><%= title %></h2>
<table>
<% for(var i=0; i<countries.length; i++) {%>
   <tr><td><%= countries[i].name %> </td>
        <td><%= countries[i].population %> million </td></tr>
   <% } %>
</table>
</body>
</html>

7. Then being in the node-template folder, run

node server.js

This would require, as you can see it, having the pages tightly coupled with the logic and that is not good.

What is needed for this then is, a separate front end from the nodejs

Next: Quick introduction to Angular js

how to get user input and process it in nodejs tutorial

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

Now we have advanced a bit more and have served an html file from node js in this tutorial.

It would be a matter of updating the html file to have the user input box and adding one more route in node js to wait for specific url, getting the input and posting back the processed data.

In this part, the app will accept a name from the user and will print an email address containing the name that is provided.

How to get input from the user

If you have followed this tutorial, start from number 4

1. create a directory node-input

2. move to that directory and issue the following command to install express in it

sudo npm install express

3. The above command would install express package in node_modules folder. This is the folder where all third party packages would be stored.

4. create server.js file in the folder node-input and add the following snippet in it.


 var express = require("express");
 
 //use the application off of express.
 var app = express();
 
 //define the route for "/"
 app.get("/", function (request, response){
     response.sendFile(__dirname+"/views/index.html");
 });
 
 app.get("/getemail", function (request, response){
     var firstname = request.query.firstname;
 
     if (firstname != "") {
         response.send("Your email address is " + firstname + "@gullele.com");
     } else {
         response.send("Please provide us first name");
     }
 });
 
 //start the server
 app.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

5. create a folder views in node-input folder

6. create index.html inside views and add the following code in it


<html>
    <head>
        <title>Simple hello world</title>
        <style>
            .prompt {
                font-size: 16px;
                color: brown;
                font-weight: bold;
                margin-bottom: 5px;
            }
            .container {
                width: 50%;
            }
            .left-pane {
                width: 50%;
                float: left;
            }
            .right-pane {
                width: 50%;
                float: right;
            }
            .submit-name {
                clear: both;
            }
        </style>
    </head>
<body>
    <h1>Hello Node JS</h1>

    <form method='GET' action="/getemail">
        <div class="container">
            <div class="prompt left-pane">
                <span>Give us your firstname and get email address</span>
            </div>
            <div class="right-pane">
                <input type="text" id="firstname" name="firstname" />
            </div>
        </div>
        <div class="submit-name">
            <input type="submit" value="get the email" />
        </div>
        </div>
    </form>
</body>
</html>

7. Save this file and start the sever using

node server.js

8. Now go to browser and surf http://localhost:8080

As you can see, the main point here would be adding one more route app.get("/getemail", function (request, response){ and accessing the parameters using the request object then passing the response with processed name in it.

The next would be to see how node can accomplish rendering the next page with values. And for that, there is a need to have template engine introduced.

Next: Using template engine ejs with node js

how to display html files from node js example tutorial

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

Here We have see how to print a Hello World for a request of “/”. That is a good advancement but that won’t give us much to proceed. We need a way to server html files for different requests.

So, what we want to do is to have more flexibility by having html file. We will have all the contents as we wish using the old school html tag and we will serve that through node js.

Displaying and rendering html file through node js

If you have followed this then start from number 4

1. create a directory node-input

2. move to that directory and issue the following command to install express in it

sudo npm install express

3. The above command would install express package in node_modules folder. This is the folder where all third party packages would be stored.

4. create server.js file in the folder node-input.


 var express = require("express");
 
 //use the application off of express.
 var app = express();
 
 //define the route for "/"
 app.get("/", function (request, response){
     //show this file when the "/" is requested
     response.sendFile(__dirname+"/views/index.html");
 });
 
 //start the server
 app.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

5. create a folder views in node-input folder

6. create index.html inside views and add the following code in it


 <html>
 <head><title>Simple hello world</title></head>
 <body>
 <h1>Hello Node JS</h1>
 </body>
 </html>

7. go to your browser and type http://localhost:8080

You will see Hello Node Js on the browser big and bold.

What is going on

It is like the previous example except we are serving the actual physical html file this time.

By doing so, we have more control on the html file like adding css and javascript codes or calling those files on the page.

Mind you, index.html is the entry point, once we got on that page, we can navigate to other pages and do more

**If the above app is not working for whatever reason, make sure to update npm and get newest version

npm i -g npm-check-updates
npm-check-updates -u
npm insert

Next: Accepting input from the user and processing it.

using express package in node – installation and usage example tutorial

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

By far, you have seen how to write to the console and to display hello world through web using node.

But, showing simply Hello World is not that interesting and fun at all. And it doesn’t show anything that simulates real world example of accepting input from user and processing that.

Before doing that, lets see the express package which would enable us to do that.

installing express package and creating a page with input boxes.

1. create a directory node-input

2. move to that directory and issue the following command to install express in it

sudo npm install express

3. The above command would install express package in node_modules folder. This is the folder where all third party packages would be stored.

4. create server.js file in the folder node-input.

5. add the following code into server.js file.


 var express = require("express");
 var app = express();
 
 app.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

6. Go to command line and start the web server, by now we know how to start the web server as

node server.js

Now you will see something interesting when you go to browser and type http://localhost:8080.

This time you would get Cannot GET / Unlike the previous time.

What is going on

express is framework that would make life way easier for the http communication between the nodejs server and whoever wants the request.

Among other things, it handle the http verbs, GET POST, DELETE, PUT, also it make the routing very easier. That is when you want to access some pages with something like http://gullele.com/list or http://gullele.com/register. That means the /list and /register are handles through routing mechanisms of express.

Ok, lets fix the that “Cannot GET /” error.

Update the server.js as follows

                                                                                                                                                                        
 var express = require("express");
 
 //use the application off of express.
 var app = express();
 
 //define the route for "/"
 app.get("/", function (request, response){
     response.end("Hello World");
 });
 
 //start the server
 app.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

Now you will see Hello World on your browser when you type http://localhost:8080.

This time, we have created a router to response when the user lands on the root of the website.

Next: Serving html files from node js

a hello world tutorial using node js with http web server

This is a continuation of the tutorial started on node js angular and mongo db shown on
node js console tutorial

In order to have simple website that is displaying hello world, we need to have a web server. In the previous example there was no need to have a web server since the message was shown from command line.

Node provides its own web server that we can serve http request and responses.

I will cover on the later tutorial how those would be used, for now. All we need is to be able to go to http://localhost:8080 and see the the output of hello world

Serving the page through web server

If you have followed the above tutorial listed on the link, start from number 3.

1. Create a folder in your computer and name it as node-tutorial

2. In the node-tutorial folder create server.js file

3. On server.js add the following code in it and save it.


 var http = require("http");
 var server = http.createServer(function (request, response) {
 response.writeHead(200, {"Content-Type":"text/plain"});
 response.end("Hello World");
 });
 
 server.listen(8080);
 
 console.log("Something awesome to happen at http://localhost:8080");

4. go to your browser and type http://localhost:8080 and you will see Hello World being printed on your browser.

Congratulations! you have successfully created a website that prints Hello World.

What is going on

The above snippet creates a very basic yet full fledged web server. At the heart of any web server are request and response

request is what the browser behalf of the user is sending to the server and it waits for the server to give it back something to show to the user. The request is the one that contains the form elements usually

response is what the server would be responding based on the request forwarded to the server. It contains usually the type of the response data, like text or json or image through its header and the actual data to be returned.

require("http"); This part tells node to import the http package for usage.

With the hello world example above, the request contains no input fields but it is full request in that it is requesting for the response of hello world.

Don’t worry if you don’t get much of the request response stuff, as it would be clear on the upcoming parts of this tutorial.

Since simply printing Hello Worlds is not that much fun. We will see how to do some other exciting stuffs on the upcoming parts of tutorials.

Next: Accept input from the browser/user and process the input

node js server downloads text/html as file on browser

Those of you who work with webserver, like apache, might already have seen that problem – like the php file that was intended to display content would be downloaded as file.. this has some fix on configuration right..
Now coming to node js, once you install the server like

  1 var http_server=require("http");
  2 http_server.createServer(function(request, response){
  3     response.writeHead(200, {'Content-Type': "text/html"});
  4     response.write("I am listening @port 8896");
  5     response.end();
  6 }).listen(8896);

This should run fine once you run node filename.js where filename.js is the file containing the above code.
but, when you try to run by going to localhost:8896 and in place of seeing the text on your browser, if the browser decided to download the file, give a a careful look at line number 3 to be sure that you have specified correct content type..