· Node.js is a platform that allows JavaScript to be used outside the Web Browsers, for creating web and network applications. This means that you can create the server and server-side code for an application like most of the other web languages but using JavaScript
Node.js is a very powerful JavaScript-based platform built on Google Chrome’s JavaScript V8 Engine. It is used to develop non-blocking I/O intensive web applications like video streaming sites, single-page applications, and other web applications. Node.js is open source, completely free, and used by thousands of developers around the world. With Node.js you can easily Node.js can generate dynamic page content, automate creating, open, read, write, delete, and close files on the server, and add, delete, modify data in your database.
Make sure that you installed Node.js on your system. If not; the official Node.js website has installation instructions for Node.js: https://nodejs.org .
Node.js uses JavaScript as the programming language.
Object based language VS object oriented language
Object oriented programming languages follow all concepts belonging to OOP. Object-based language doesn’t support all the features of OOPs like Polymorphism and Inheritance Object-based language has in-built object like JavaScript has window object. Object-based languages are JavaScript. JavaScript has built in mechanism similar to classes by using function; inheritance is performed by using prototype. Here is quick tutorial on how to create / inherit objects in JavaScript.
Below is a quick intro to JavaScript
<script> /* A quick introduction to JavaScriptcript. All you need is an editor with linenumber such as textpad or notepad++, and browser (IE, Chrome, Firefoxe, and Safari) Sammy Abaza */ /* to learn any programming language you must learn the following 1- declare and use variables 2- using if-then 3- looping */ /* advanced topics functions() objects and classes */ // declare variables var firstName var lastName firstName=”Sammy” lastName=”Abaza” var fullName=lastName+”, “+firstName alert(“My Name is “+ fullName)
// if-then var myID=”007″ if(myID==”007”) { alert(“You are Bond, James Bond”) } else { alert(“You are Bundy, Al Bundy”) }
// loop 10 times for(i=0;i<10;i++) { document.write(“Hello “+i +”\n”) //\n for new line } //function is a group of code with a name, function return a value function addTwoNum(num1, num2) { return num1+num2 } //test var result=addTwoNum(10, 20) alert(result) </script> <script> // this is a function in class style function person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; this.name=name; } function name() // this is a function of the class { return this.firstName + ” ” + this.lastName }; // adding a new function to the existing class, so name2 is part of the person class(function) person.prototype.name2 = function() { return this.lastName + “, ” +this.firstName ; }; // testing var myFather = new person(“Sammy”, “Abaza”, 50, “blue”); document.getElementById(“demo”).innerHTML = “My father is ” + myFather.name(); document.getElementById(“demo”).innerHTML += ” <br/> My father is ” + myFather.name2(); /****************************************************** Practice, 1) Add more functions to the above class 2) Create your own class 3) Create functions with parameters
4) Practice logical operator &&, ||, and ! (and, or, and not) ******************************************************/ < /script>
How to run a Node.js program?
If you installed and configured Node.js correctly, you should be able to run Node.js from anywhere from your computer. Just type Node.
C:\ENTD261>Node << you will see this
>
You can exit Node.js by typing this process.exit(-1);
> process.exit(-1);
Or press CTRL+C twice.
Let us write a simple program
In C:\ENTD261 write the following
console.log(“Hello, class from ENTD261 Node.js console”)
Save it as wk4_01.js
From command prompt
>Node wk4_01.js
You will get
Hello, class from ENTD261 Node.js console
Node.js and arguments
Since most of your code will be from command line, passing parameters maybe necessary to make the code usable, make sure that you document your work. Here is how to pass argument to Node.js program.
Create the following code and save it in wk4_args.js
console.log(process.argv);
>node wk4_args.js
You will get something like this;
[ ‘C:\\nodejs\\node.exe’, ‘C:\\ENTD261\\w4_args.js’]
Now comment the above code and add the following code;
// console.log(process.argv);
if (process.argv.length <= 2) {
console.log(“Usage: ” + ” SOME_PARAM”);
process.exit(-1);
}
console.log(‘Params: ‘ + process.argv.length);
console.log(‘University: ‘ + process.argv[2]);
console.log(‘Class: ‘ + process.argv[3]);
// Test the code
// node w4_args.js
// node w4_args.js Apus ENTD261
Now uncomment the above line and run the code again, pay attention to the results. To debug any of the code, use console.log to examine the variables where you have an issue.
See http://nodeguide.com/beginner.html#learning-javascript
What is NPM?
NPM, short for Node Package Manager, is two things: first, it is an online repository for the publishing of open-source Node.js projects; there are over 10,000 libraries on npm. Please check the recent updates for any library before using it. Second, it is a command-line utility for interacting with the repository that aids in package installation, version management, and dependency management.
To test npm, from c:\ENTD261>npm –version or npm –help
In the next section we will install a webserver Express.js using NPM.
What Express.js
Express.js is a Node.js framework adds on. It is a web application framework for Node.js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs. It is the de facto standard server framework for Node.js. Also it is a part of widely used stack called the MEAN stack. https://en.wikipedia.org/wiki/Express.js
To install express using npm
C:\entd261>npm install express.js –save
For more information see http://expressjs.com/en/starter/installing.html
What do you mean by Asynchronous call in Node.js?
In JavaScript and Node.js there is a queue of events that is handled by the runtime engine. The runtime engine processes the events in the events queue. When an event is generated by code or by user interaction it is stored in the queue events. When an event happens the program executes a pre-defined function that handles the event.
Now you need to compare this with traditional programming. In traditional case the applications gets the data, then do a series of steps serially or parallel and send the result back to the caller. Generally you don’t know when the data will arrive, the application just keep polling using a loop.
In JavaScript that polling is done by the runtime engine itself. So it keeps polling for an event and when an event occurs it notifies you (pretty cool). Now in Node.js, the events are also raised by network connections. When a client connects to the server event is raised and the application acts accordingly to the event. So it is event driven. Now events are async. Events can come anytime in any sequence. There is no fixed time when an event (a connection request for example) will be raised.
In summary in async programming events do not wait for each other, each event runs in its own process. So if you have 10 processes running and the first on dies for any reason, the other nine will continue to work. In traditional programming the entire application will die.
What are MV* frameworks?
MV* (MVC, MVP, and MVVM)
MVC is an architectural design pattern that encourages improved application organization through a separation of concerns. It enforces the isolation of business data (Models) from user interfaces (Views), with a third component (Controllers) traditionally managing logic and user input.
A Model represented domain-specific data and is ignorant of the user interface (Views and Controllers). When a model changed, it would inform its observers.
A View represented the current state of a Model. View-Controller pair was required for each section or element displayed on the screen. The Controller’s role in this pair was handling user interaction (such as key presses and actions such as clicks), making decisions for the View
In this section, we are going to review the three known architectural patterns: MVC (Model- View-Controller), MVP (Model-View-Presenter), and MVVM (Model-View-ViewModel). The majority of JavaScript/web developers are currently using these patterns.
These days, the MVC pattern applied to a diverse range of programming languages, including JavaScript. JavaScript now has a number of frameworks boasting support for MVC. These frameworks include the likes of Backbone, Ember.js, and AngularJS. Given the importance of avoiding “spaghetti” code, it is very important that the modern JavaScript developer understand what a pattern provides.
What Does MV* Give Us?
This separation of concerns in MVC facilitates simpler modularization of an application’s functionality and enables the following:-
Easy maintenance, when updates are very clear whether the changes are data-centric, meaning changes to models and possibly controllers, or merely visual, meaning changes to views.
Decoupling models and views means that it is significantly, more straightforward to write unit tests for business logic.
Depending on the size of the application and separation of roles, this modularity allows developers responsible for core logic and developers working on the user interfaces to work simultaneously. (See MVC diagram)
MVP (Models, Views, Presenters)
Model View Presenter (MVP) is a derivative of the MVC design pattern that concentrates on presentation logic. Both MVC and MVP target the separation of concerns across multiple components.
The P in MVP stands for presenter. It’s a component that contains the user-interface business logic for the view. Unlike MVC, invocations from the view are delegated to the presenter, which are decoupled from the view and instead talk to it through an interface. This allows for all kinds of useful things, such as being able to mock views in unit tests (See MVP diagram)
The most common implementation of MVP is one that uses a Passive View (“dumb view”), containing little to no logic. If MVC and MVP are different, it is because the C and P do different things. In MVP, the P observes models and updates views when models change. The P effectively binds models to views, a responsibility that was previously held by controllers in MVC.
Solicited by a view, presenters execute any user requests and pass data back to them. In this respect, they retrieve data, manipulate it, and determine how the data should be displayed in the view. In some implementations, the presenter also interacts with a service layer to persist data (models). Models may trigger events, but it’s the presenter’s role to subscribe to them so that it can update the view. In this passive architecture, there is no concept of direct data binding. Views expose setters that presenters can use to set data.
The benefit of this change from MVC is that it increases the testability of our application and provides a more clean separation between the view and the model. However the data binding support in the pattern is a separate task.
MVVM
MVVM (Model View ViewModel) is an architectural pattern based on MVC and MVP, which attempts to more clearly separate the development of user interfaces (UI) from that of the business logic and behavior in an application. Many implementations of this pattern make use of declarative data bindings to allow a separation of work on Views from other layers.
UI developers write bindings to the ViewModel within their document markup (HTML), where the Model and ViewModel are maintained by developers working on the logic (business rules) for the application (See MVVM diagram).
Model, as with other members of the MV* family, the Model in MVVM represents domain-specific data that the application will be working with. A typical example of domain-specific data might be a music track (e.g., title, year, album, band) or a user account (e.g., name, address, phone, email)
Models hold information; behavior is considered business logic that is implemented in another layer that interacts with the Model: the ViewModel.
The only exception to this rule tends to be validation, and it’s considered acceptable for Models to validate data being used to define or update existing models.
View, as with MVC, the View is the only part of the application that users actually interact with. They are an interactive UI that represents the state of a ViewModel. In this sense, the view is considered active rather than passive, but this is also true for views in MVC and MVP. In MVC, MVP, and MVVM, a view can also be passive, but what does this mean?
A passive View only outputs a display and does not accept any user input. Such a view may also have no real knowledge of the models in our application and could be manipulated by a presenter. MVVM’s active View contains the data bindings, events, and behaviors, which requires an understanding of the ViewModel. Although these behaviors can be mapped to properties, the View is still responsible for handling events from the ViewModel.
It’s important to remember the View isn’t responsible here for handling state; it keeps this in sync with the ViewModel.
ViewModel, the ViewModel can be considered a specialized Controller that acts as a data converter. It changes Model data into View information, passing commands from the View to the Model.
The ViewModel might be looked upon as more of a Model than a View, but it does handle most of the View’s display logic. The ViewModel may also expose methods for helping to maintain the View’s state, update the model based on the actions on a View, and trigger events on the View. The ViewModel sits behind the UI layer. It exposes data needed by a View from a Model.
Creating MVC application with node.js and express.js
One of the most popular Node.js web frameworks is “ExpressJS”, which simplifies the process of setting up a web server capable of responding to requests to different URLs using whichever type of HTTP method, for example, GET or POST, is required. The desired behavior for each URL can then be coded in JavaScript to simply respond with a HTML page, or to process submitted form data.
ReST (Representational State Transfer), is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability that enable services to work best on the Web
ReST architecture provides a simple way access to resources from ReST client Eeach resource is identified by URIs/ global IDs. ReST uses various representations to represent a resource like text, JSON and XML. Now days JSON is the most popular format being used in web services.
Following are the most used HTTP methods in ReST based architecture.
o GET – Provides a read only access to a resource.
o PUT – Used to update an existing resource.
o DELETE – Used to remove a resource.
o POST – Used to create a new resource.
ReSTFul Web Services
A web service is a collection protocols and standards used for exchanging data between applications or systems. Services are written in various programming languages, and running on various platforms. The following table has URI examples on how to call the services.
Routing Table
Sr. No. | HTTP Method | URI | Operation | CRUD |
1 | GET | /UserService/users | Get list of users | Read |
2 | GET | /UserService/users/1 | Get User with Id 1 | Read |
3 | PUT | /UserService/users/2 | Insert User with Id 2 | Update |
4 | POST | /UserService/users/2 | Update User with Id 2 | Create |
5 | DELETE | /UserService/users/1 | Delete User with Id 1 | Delete |
With ExpressJS, you can easily create a ReStful web services.
Here is an example with to create a routing table similar to the one above
/*
// This application to demo the use of restfull services
// This is the core for any MV* pattern
// let me know if you have any question
// use express server, it must be in the node_modules
save this code as wk4_myserver.js in c:\ENTD261
to run this code, make sure you are on c:\entd261 if not change directory to c:\entd261
>cd c:\entd261
C:\ENTD261>node wk4_myserver.js
once the server is running, you will get
Express server listening on port 55555
from any browser
http://localhost:55555/
*/
// setup
var express=require(“express”);
var http=require(“http”);
var app=express();
// run the server
http.createServer(app).listen(55555);
console.log(‘Express server listening on port 55555’);
// <<< here is the Model, the data storage
var products = [
{ id: 0, name: ‘watch’, description: ‘Tell time with this amazing watch’, price: 30.00 },
{ id: 1, name: ‘sandals’, description: ‘Walk in comfort with these sandals’, price: 10.00 },
{ id: 2, name: ‘sunglasses’, description: ‘Protect your eyes in style’, price: 25.00 }
];
// http://localhost:55555 // general route
// here is the view
app.get(“/”, function(req,res){
var msg=””
msg += “<center><h1> This is the default page </h1></center>”
msg += ” use the following <br />”
msg += ” http://localhost:55555/hello <br />”
msg += ” http://localhost:55555/goodbye <br />”
msg += ” http://localhost:55555/products <br />”
msg += ” http://localhost:55555/products/2 <br />”
res.send(msg);
});
// <<< routes = controller
// http://localhost:55555/hello // welcome route
app.get(“/hello”, function(req,res){
res.send(“Hello ENTD261 class”);
});
// http://localhost:55555/goodbye // good bye route
app.get(“/goodbye”, function(req,res){
res.send(“Thank you ENTD261 class”);
});
// http://localhost:55555/products // load and display all products
app.get(‘/products’, function(req, res) {
res.send(JSON.stringify(products));
});
// http://localhost:55555/products/2 // load and display product id 2
app.get(‘/products/:id’, function(req, res) {
if (req.params.id > (products.length – 1) || req.params.id < 0) {
res.statusCode = 404;
res.end(‘Not Found’);
}
res.send(JSON.stringify(products[req.params.id]));
});
To do for practice:
1) Create a routing table from the application similar to the routing above
2) Create an application based on the above routing table
3) Modify the application to print a useful message when requesting incorrect id.
4) Store the data to external file instead of hard coding them
5) Store the data into external storage (Excel, MySQL or MongoDB)
What is the MEAN Stack?
The MEAN stack represents simplicity of design to a collection of a JavaScript based technologies used to develop applications (web and non-web). MEAN is an acronym for MongoDB, ExpressJS, AngularJS and Node.js. From client to server to database, MEAN is full stack JavaScript. The MEAN stack is very popular and in demand. It is used by application developers and administrators to automate daily tasks easily. It is any easy way to connect to any database. MongoDB is a NoSQL document database that is very flexible and used to house Big Data. For more information see https://www.sitepoint.com/introduction-mean-stack/
Creating command line application
In prior section we created a simple command line application with arguments, in this section we will expand on that concept.
Reading a file Read file in asynchronously (non-blocking)
Create the following code as wk4_readfile.js
var fs = require(‘fs’);
filename = process.argv[2]
fs.readFile(filename, ‘utf8’, function(err, contents) {
console.log(contents);
});
console.log(‘after calling readFile’);
// to run c:\ENTD261>node wk4_readfile.js wk4_readfile.js
// you should see the above file printed.
Now we are going to create the same thing the traditional way, the blocking way.
var fs = require(‘fs’);
filename = process.argv[2]
var fs = require(‘fs’);
var contents = fs.readFileSync(filename, ‘utf8’);
console.log(contents)
console.log(‘after calling readFile’);
Now let us run the following code to get info/stats about a folder, save the code below in wk4_stats.js
var fs = require(‘fs’);
if (process.argv.length <= 2) {
console.log(“Usage: ” + __filename + ” path/to”);
process.exit(-1);
}
var path = process.argv[2];
fs.stat(path, function(err, stats) {
console.log(path);
console.log();
console.log(stats);
console.log();
if (stats.isFile()) {
console.log(‘ file’);
}
if (stats.isDirectory()) {
console.log(‘ directory’);
}
console.log(‘ size: ‘ + stats[“size”]);
console.log(‘ mode: ‘ + stats[“mode”]);
console.log(‘ others eXecute: ‘ + (stats[“mode”] & 1 ? ‘x’ : ‘-‘));
console.log(‘ others Write: ‘ + (stats[“mode”] & 2 ? ‘w’ : ‘-‘));
console.log(‘ others Read: ‘ + (stats[“mode”] & 4 ? ‘r’ : ‘-‘));
console.log(‘ group eXecute: ‘ + (stats[“mode”] & 10 ? ‘x’ : ‘-‘));
console.log(‘ group Write: ‘ + (stats[“mode”] & 20 ? ‘w’ : ‘-‘));
console.log(‘ group Read: ‘ + (stats[“mode”] & 40 ? ‘r’ : ‘-‘));
console.log(‘ owner eXecute: ‘ + (stats[“mode”] & 100 ? ‘x’ : ‘-‘));
console.log(‘ owner Write: ‘ + (stats[“mode”] & 200 ? ‘w’ : ‘-‘));
console.log(‘ owner Read: ‘ + (stats[“mode”] & 400 ? ‘r’ : ‘-‘));
console.log(‘ file: ‘ + (stats[“mode”] & 0100000 ? ‘f’ : ‘-‘));
console.log(‘ directory: ‘ + (stats[“mode”] & 0040000 ? ‘d’ : ‘-‘));
});
// to run this code c:\ENTD261> node wk4_stats.js c:\ENTD261
// The code is self-explanatory for more info see https://code-maven.com/system-information-about-a-file-or-directory-in-nodejs
Here is another sample code for admin to list the content of the directory;
var fs = require(‘fs’);
if (process.argv.length <= 2) {
console.log(“Usage: ” + __filename + ” path/to/directory”);
process.exit(-1);
}
var path = process.argv[2];
fs.readdir(path, function(err, items) {
console.log(items);
for (var i=0; i<items.length; i++) {
console.log(items[i]);
}