Share Tweet Reccomend

Debugging Node.js Applications with Node Inspector

Debugging is an important part any sort of application development. If you have errors or unexpected results occurring in your code you need to be able to step through your code and find where things are going awry. Thus it is very important that you are able to see what is happening at specific times when your code is executing. There are some IDEs (integrated development environments like Visual Studio or Eclipse) where debugging for the native application language like C# or Java is all built right into the tools and you don’t have to do anything to set it up. At the time of this writing in the later part of the year 2015, there are a few IDEs such as WebStorm and Komodo IDE that natively support Node.js debugging but this is often the exception rather than the rule (at present). Node.js, being a younger and relatively more immature platform often does not have debugging for it natively implemented in most IDEs yet. Fortunately, there are often plugins available that will enable Node.js debugging within the IDE. Node.js tools for Visual Studio 2012 and 2013 is one example. Nodeclipse is a plugin that will enable Node.js debugging capabilities in Eclipse.

Because there are so many different development environments and workflows that different developers have different preferences for we won’t look at debugging Node.js applications in a specific IDE. But we will look at a specific debugger called Node Inspector. There are other Node.js debuggers out there and if you want to use another debugger that is fine. You would just have to look at the docs for that particular debugger. It should be noted that Node Inspector works in Chrome and Opera only. You have to re-open the inspector page in one of those browsers if another browser is your default web browser (e.g. Safari or Internet Explorer). This is another indicator that shows widespread support for many things in and within Node.js is not entirely quite there just yet. So much of the Node.js module ecosystem is community driven, which has very noticeable pros and cons. The upside to this it is that there are a lot of awesome components of functionality that you can leverage via installation with a simple $ npm install of a module. The downside of this environment is that support and/or consistency for bug fixes and releases can vary quite a bit depending on who’s module(s) you are using. Just as a personal opinion, I find that on the whole the positives outweigh the negatives when it comes to open source software. I would much rather take this scenario over, say, a behemoth corporation owning and managing all of the releases that might seem more “professional” in its support and maintenance (as opposed to hobby/side-project code). But developing in and for open source applications is definitely far from perfect.

But all that aside, let’s get back to fun with Node.js debugging. Node Inspector works almost exactly as the Google Chrome Developer Tools. If you are not entirely familiar with Google Chrome’s developer tools read the DevTools overview to get started. Dev Tools can be used to set breakpoints in your application that halt the execution of the code when a certain statement (or statements) are reached. From there you can examine the state of particular objects to see what values they contain at that point in time. You can then step through your code moving from one statement to the next to see how the values change. If this all seems a little bit confusing at this point, not to worry. We will revisit this a bit later when we actually take on the task of debugging our application. But first we need to install the stuff we need to get debugging up and going.

Installing Node Inspector

To install Node inspector we will use the npm utility to install Node Inspector from npm.

$ sudo npm install -g node-inspector

Note: Windows 8.1 Users: At the time of this writing in the later part of 2015 for Windows 8.1 I had to omit installing an optional dependency which apparently breaks the install using npm. The way that you do this is by setting the –no-optional flag…

$ npm install -g node-inspector --no-optional

That should get it working for you. To check that it installed correctly you can always run

$ node-debug --version

which should output the version number for you without any error messages.

Sample Application

For our application we will use a sample API that I often utilize for demonstrating Node.js applications that uses Express.js as an application framework. If you are not familiar with Express there is an introduction to Express here. If you need a quick refresher on Node.js by any chance you can read A Node.js Primer. For a more in-depth look at Express.js, there is also an ongoing series entitled Creating an MVC Express.js Application.

Read More »

Share Tweet Reccomend

Basic Authentication in Node.js Express Applications and APIs

In the past we have looked at basic access authentication using the Slim PHP framework. In the context of an HTTP transaction, basic access authentication is a method for an HTTP user agent to provide a user name and password when making a request. It is an easy way to secure different parts of your application by prompting the user to enter credentials before you serve up the response, be it a webpage of HTML or some XML or JSON at an API endpoint. It looks something like the following in browsers…

Basic Authentication

All you need to do is send WWW-Authenticate headers to get this prompt to appear. You can also specify a realm that allows you to have different “groupings” of authentication. If a user successfully enters the their credentials for one realm they will not have to re-enter their credentials for other pages or routes protected under basic authentication in the same realm. This will last for the duration of the user’s session. However, if he or she tries to access a route under a different realm he/she will have enter credentials again (which can be the same credentials or a different name/password combination). In this manner you can have different authentications for different places within your website or web application.

When the user enters credentials, these credentials are encoded with BASE64 encoding and sent to the server. They are not encrypted or hashed in any way. Thus, it would be pretty easy for an individual on the same network to view and decode these credentials (and then possibly use them for malevolent purposes). This is what is known as a man in the middle attack (MitM) and it is one of the common security vulnerabilities that developers need to be cognisant of. You could, of course, add an additional component to security such as sending an additional hash in a cookie that can be decoded on the server. However, in order for this to be effective both the server and the client need to have a private key that is known on both ends and is not sent over the wire. Getting this key from the server to the client requires an additional step of involvement for users. Thus, probably the most straightforward way of using basic authentication in a secure manner is to use TLS/SSL and have all requests between server and client be over https://.

Whatever you decide to do, basic authentication can be a decent solution for security if it is used properly.

So in what follows we will take a look and see how we can implement this in a Node.js application that uses Express.js as an application framework. Before looking at the following section, it might be a good idea to be familiar with Express.js by reading the introduction to Express and be familiar with Node.js as well. Another article entitled A Node.js Primer will help you with that. For a more in-depth look at Express.js, there is also an ongoing series of posts that discusses how to create an MVC Express.js Application that covers many different aspects of using Express.js.

Read More »

Share Tweet Reccomend

Introduction to React

React is a JavaScript library that is primarily responsible for handling the “view” component of a JavaScript single-page application. As it describes itself of the React homepage…

Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it’s easy to try it out on a small feature in an existing project.

React’s focus, first and foremost, has to do with rendering dynamic UIs in a manner that is visually appealing to the user. It is flexible enough that it can be used in a diversity of capacities and contexts. We mentioned earlier that there are a number of different MVW/MV* JavaScript frameworks and all of them have different implementations in how they handle the various aspects of a JavaScript application. Naturally they all have different ways that they handle rendering visual representations of the data that the application is handling. Backbone.js natively uses Underscore.js templates, Ember users Handlebars.js, and Knockout.js and Angular have their own syntax. With a little bit of work you can swap view engines within these frameworks if you so choose. And it would be here where we could incorporate React to handle the view rendering portion of an application. But, as mentioned above, React is not dependent on any JavaScript framework being in place. It can be used as a standalone aspect of an application almost entirely independent from any other library or environment.

So why go to the trouble to incorporate React? Why not just use a framework’s native rendering engine (if you are using a framework). If you are not using a framework, why not just use something like jQuery to handle your view layer? Again, looking at the React homepage, the following description is provided…

React abstracts away the DOM from you, giving a simpler programming model and better performance. React can also render on the server using Node, and it can power native apps using React Native.

As it turns out there are a number of different positive aspects in terms of performance, scalability, and simplicity that React can provide to application development as it progresses along in both size and complexity. We will explore these in detail as we go forward. As many have noticed, React is a little bit unorthodox from “traditional” JavaScript application development (if there were such a thing) and it can take a little bit of working with it and a little bit of trial and error before many of the benefits of it are fully realized. Indeed, many developers admit that they did not quite “get it” at first and some have even described a substantial initial aversion to some of its implementations. So if you experience this on any level, you are definitely not alone and I would merely invite you to “stick with it” through some of the initial tutorials before you run for the hills screaming in terror. Who knows? You just might be surprised at the end of the day.

Note: For the following discussions want to run our various projects inside of a localhost HTTP web server. If you have a local Apache or IIS setup you may wish to use this by putting the files that you create in the upcoming tutorials in a directory created inside the www folder. Another quick easy implementation is to just pull down the Node.js http-server module by running the following from your command line…

$ npm install -g http-server

From there you can create a directory anywhere you like and run the following…

$ http-server

This will run an HTTP server at localhost:8080. If you got to https://localhost:8080 you should see something there that tells you a server is running.

React is a view rendering JavaScript library that is created and maintained by a team of engineers at Facebook. It is responsible for dynamically handling the visual display of various components within a web site or web application in a flexible, efficient, and interactive manner. What this often means is that React handles the displaying of the data that underlies an application and will dynamically update everything that it needs to in a performance conscious manner when that data changes. We will look at all of React’s various components that come together to make this happen in greater detail as we go along in the upcoming tutorials.

Perhaps the best thing to do is to jump right in and get our first look at React. To start out we will need an index.html file. So create a new file in a directory where you want to run things from and create a file called index.html. In this file place the following code…

<!DOCTYPE html>
<html>
<head>
    <title>React</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>        
    <script src="https://fb.me/react-0.12.2.js"></script>
    <script src="https://fb.me/JSXTransformer-0.12.2.js"></script>

</body>
</html>

So we are first loading up the React library over CDN and we are also loading up something called the “JSXTransformer.” React has its own programming language called JSX. It is React’s own special easy-to-read abstracted syntax that in the end gets converted to native JavaScript. It is important to note that using JSX is optional. It is not required to create React applications and you can write your React components in native JavaScript if you so choose. For a lot of the upcoming examples provided in what is to follow, we will look at the same code written in both JSX and native JavaScript and you can decide which is more appealing to you. We will discuss the pros and cons of leveraging JSX bit later on as well.

Hello World in React

So now that we have React loaded up, let’s write our first React component. We will do the obligatory “Hello World” example that has so ubiquitous throughout programming tutorials since the dawn of time. We are going to personalize this a bit more though and we are going to say “hello” to an individual rather than the entire world.

JSX

So let’s start by looking at the JSX syntax just to get a look at it. Create a folder called “js” and create a file called hello.jsx and include it after the scripts like so…

<!DOCTYPE html>
<html>
<head>
    <title>React</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>        
    <script src="https://fb.me/react-0.12.2.js"></script>
    <script src="https://fb.me/JSXTransformer-0.12.2.js"></script>
    <script type="text/jsx" src="js/hello.jsx"></script>
</body>
</html>

In this file add the following JSX code…

var HelloMessage = React.createClass({
    render: function() {
        return <div>Hello {this.props.name}</div>;
    }
});

React.render(<HelloMessage name="John" />, document.body);

Now let’s open this index.html in your favorite browser in your web server. You should see the message “Hello John” displayed. Congratulations, you have just written your first React component!

Read More »

Share Tweet Reccomend

An Angular 2 Primer

Angular 2 is the much anticipated latest release of the Angular platform maintained by a team of engineers over at Google. The first iteration of Angular (which we may refer to as Angular 1 or 1.X at times) was and has been very well received within the JavaScript community. Many saw it as an improvement on smaller single-page application libraries like Backbone.js and Knockout.js because it essentially did “more” for you. You got a lot of functionality out of the box with the result being that you had to write less boilerplate code than you would with using a more basic library. Directives allow you to define custom attributes for any element that you want and Angular also boasts other great features such as native data-binding, an AMD like module loading system, and services using a solid promise implementation for asynchronous data transfer. All of this and more comes pre-packaged within Angular and is coupled with a great community behind it, an abundance of resources, as well as great support from the team over at Google. Because of all this, it is not too surprising that many companies and organizations have turned to it as a solution for building their web and mobile applications.

If there were a few points of criticism of Angular as a framework, it usually surrounded a slightly steeper learning curve when compared to other libraries, and the observation that perhaps there was a little “too much magic” going on under the hood without the developer really fully understanding what is happening 100% in all circumstances. This is always a double-edged sword with a framework that gives you a lot of functionality out of the box. On one hand, it is great to have a system where writing a relatively small amount of code will give you a lot of dynamic features and functionality with minimal effort. On the other hand, this sometimes requires that you follow a very defined and specific pattern in the way that you structure your code and if you ever want to do something that is perhaps a bit unorthodox from the accepted way, it might not be so easy and a framework that is a bit more rigid when it comes to custom implementations not always desired — especially when those hard-to-track-down bugs surface at inopportune times. Like with so many things, there will always be pros and cons to any technology you encounter.

Nonetheless, the reception and response to Angular 1 was/is overall very positive. It was often paired with Node.js development using the web application framework Express.js and the NoSQL database MongoDB to create what was known as the MEAN stack (MongoDB, Express, Angular, Node.js). Many readers may be familiar with this and other technology paring acronyms (such as LAMP: Linux, Apache, MySQL, and PHP or Python). When certain groupings of technologies complement each other well and play together nicely, it always makes for a better development experience all around.

Angular 2 Announcement and Pushback

In the latter part of 2014 Google announced that they were developing Angular 2. Usually these sorts of announcements are met with are met with a lot of excitement. After all, who wouldn’t like a shiny new version of something that you already like. However there was one overarching dark cloud the loomed over the Angular 2 announcement that was met with a lot of frustration within the web development community: Angular 2 would be essentially a rewrite of the codebase and drastically different enough from Angular 1.X such that there would be no foreseeable upgrade path to move from Angular 1.X to Angular 2. This meant that existing applications in Angular 1.X would essentially have to be rewritten. On top of this, it was not immediately clear how long Angular 1.X would continue to be supported with new releases and bug fixes.

Naturally, of course, some developers were upset by this. Only time will tell what the full impact of this decision and approach will be. Nonetheless, we move forward towards the future regardless of how much of the past comes along with it. That’s what we are aiming to do in the following discussions and tutorials.

NOTE: At the time of this writing it is still not entirely clear whether any of this will change and the Angular team will put an upgrade path in place. Also note, at the time of this writing in mid-2015, Angular 2 is still in “developer preview.” This means that many of the concepts and code samples presented in this book are subject to change. I will do my best to keep up to date on the latest changes as they roll out, but please note that there might be some sensitivity involved with functionality between different versions of Angular 2 and its surrounding tools. If you encounter anything in this regard, please do not hesitate to contact me via the above channels.

Introduction to Angular 2

Angular 2 incorporates many modern features of the latest iterations of JavaScript and tools within the JavaScript community being released circa halfway through the second decade of the 21st century (2010 – 2020). This includes many syntactical and functional features of ECMAScript 6 — the latest iteration of JavaScript up from ECMAScript 5, Node.js based dependency management with npm , TypeScript — the type checking JavaScript utility syntax that has been built and maintained by Microsoft, and a number of others. In short, the fingerprints of many of the newest emerging technologies within the web development world during this window of time are present on the Angular 2 framework. Similar to those that have come before, each release of Angular 2 will attempt to be a more malleable and useful option for developers looking to solve the common problems that they all face.

So let’s look all of these pieces that are essential for developing an Angular 2 application…

Node.js

Angular 2 uses Node.js and more specifically npm for installation of the various dependencies it requires. Having been first published by Ryan Dahl in 2009, Node.js — the open source software that allows the common web language of JavaScript to run outside the browser — has absolutely grabbed ahold of imaginations in the world of technology in its first half-decade of life. The explosion of Node.js applications and the exponentially increasing number of published modules of npm, the repository where Node.js modules are stored, are a huge indicator of its success as a platform.

So be sure head over to the Node.js website and install it for your OS. You will definitely be needing it as we go along.

ECMAScript 6

Angular 2 uses many implementations found in ECMAScript 6, or ES6 for short. It would be beneficial to take a brief look at some of the new features found in this latest version of JavaScript up from ES5. For example, ECMAScript 6 implements a more syntactical conceptualization of classes in JavaScript. While JavaScript classes are not and never have been classes in the strictest technical sense as they are in the traditional object-oriented languages Java, C++, and C#, many JavaScript applications can still be written in a way that incorporates a very class-like implementation using functions, constructors and prototypal inheritance. For example, you will often see something the following in a JavaScript application (ES5):

// ES5
function Animal() {
    this.color = 'brown';
    this.size = 'medium';
    this.age = 1;
}
Animal.prototype.sound = function() {
    console.log('Grunt');
};
Animal.prototype.move = function() {
    console.log('Running');
};

var beast = new Animal();

Inheritance can even be implemented in this approach…

function Dog() {
    Animal.call(this);
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog

var fido = new Dog();
fido.color // brown;

By calling the Animal function and passing in the Dog function as the context, and new instance of a Dog will get all of the properties and methods found on Animal. We then do a little bit of additional cleanup with some of the prototype to make sure that the pointers are pointing at the right place.

Read More »

Share Tweet Reccomend

Creating an MVC Express.js Application (Part 4): Relational Data in MongoDB

In this section we will look at another interesting aspect of creating a web application using Node.js, Express, and MongoDB: referencing other data in the database. MongoDB is part of the NoSQL class of databases (as opposed to the traditional relational databases that have been so prevalent for so long). NoSQL databases store records as documents as opposed to relational databases which store records as rows in tables. Documents in NoSQL databases are basically collections of key value pairs sort of like JSON objects. As the MongoDB documentation describes in the introduction

A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents.

You can find many articles out on the web discussing the difference between NoSQL databases and relational databases. MongoDB is a solution to a common problem and like with many things it has its advantages and its drawbacks.

But even with their structure, NoSQL database documents still have need to store references to other objects within them (somewhat like foreign keys). We have been creating data models of books in previous examples in this tutorial that have a “title” field, an “author” field, and an “isPublished” field. We have been storing the author as a string value. But really in a real-world application we’d more likely want to store a reference to an author that exists in an authors collection elsewhere. That way we could store additional information about an author or show a collection of books written by the same author. When you start relating and connecting data in this manner your application becomes truly dynamic and useful

Setup

So let’s create an “AuthorModel” and all of the scaffolding to put an “authors” section in the database. Like we’ve done before, we’ll want to follow the same process: define our model schema for our “AuthorModel,” add routes, add controllers, and add views. We will move fairly quickly through this. A lot of what we are doing was covered earlier in this tutorial. If there are any parts that seem unclear, please go back and review the content presented earlier to get a refresher on how this application is being structured.

So let’s start by defining our author schema in our Models.js file. This one will be a bit simpler than our book model schema. All we need to add here is a name. What will be important later on is the author _id value that we can associate with a book as a reference field…

var Author = new mongoose.Schema({
    name: String
});


var BookModel = mongoose.model('Book', Book);
var UserModel = mongoose.model('User', User);
var AuthorModel = mongoose.model('Author', Author);

module.exports = {
    BookModel: BookModel,
    AuthorModel: AuthorModel,
    UserModel: UserModel
};

And let’s continue with adding our author routes to the router.js file making sure to add a refenrece to our soon-to-be-created AuthorsController…

var HomeController = require('./controllers/HomeController');
var BookController = require('./controllers/BookController');
var AuthorController = require('./controllers/AuthorController');

// Routes
module.exports = function(app){
    
    // Main Routes
    
    app.get('/', HomeController.Index);
    app.get('/other', HomeController.Other);   

    // Book Routes
    
    app.get('/books', BookController.Index);
    app.get('/books/add', BookController.BookAdd); 
    app.post('/books/add', BookController.BookCreate); 
    app.get('/books/edit/:id', BookController.BookEdit);
    app.post('/books/edit', BookController.BookUpdate); 
    app.get('/books/delete/:id', BookController.BookDelete);     

    // Author Routes
    
    app.get('/authors', AuthorController.Index);
    app.get('/authors/add', AuthorController.AuthorAdd); 
    app.post('/authors/add', AuthorController.AuthorCreate); 
    app.get('/authors/edit/:id', AuthorController.AuthorEdit);
    app.post('/authors/edit', AuthorController.AuthorUpdate); 
    app.get('/authors/delete/:id', AuthorController.AuthorDelete);  

}; 

Read More »