The Astonishing Power of High Performance JavaScript, Without The Headache or A Steep Learning Curve

Stop struggling to code front-end the hard way. React.js is performing fast DOM manipulations and is easy to learn.

I stumbled upon some guy from Zurich, Switzerland who was arguing that you don’t need MVC (model, view, controller) with React.js.

What?

I love controversial topics! How refreshing to hear such a brave opinion after almost a decade of MVC-domitaion.

VIDEO —>>>> The Astonishing Power of High Performance JavaScript, Without Headache or Steep Learning Curve from Azat Mardan on Vimeo.

Continue reading “The Astonishing Power of High Performance JavaScript, Without The Headache or A Steep Learning Curve”

Write Templates Like A Node.js Pro: Handlebars Tutorial

I’ve wrote how I struggled with Jade, but I had no choice except to master it. However, before beginning to understand Jade, I admired Handlebars GREATLY. I did it mostly for its simplicity and similarity with plain HTML.

If you want to write templates for Node.js apps, then consider Handlebars. This short tutorial will get you started on the path of becoming a pro. And if you haven’t even heard about Handlebars, then you’re missing out big time!

Here’s the outline of this post:

  • Handlebars syntax
  • Handlebars standalone usage

Continue reading “Write Templates Like A Node.js Pro: Handlebars Tutorial”

How to Write Your First Test With Mocha

The goal of this mini-project is to add a few tests for Blog.
The project is on GitHub at https://github.com/azat-co/blog-express.

We won’t get into headless browsers and UI testing, but we can send a few HTTP requests and parse their responses from the app’s REST end points.

Continue reading “How to Write Your First Test With Mocha”

How To Use Mocha With Node.js For Test-Driven Development to Avoid Pain and Ship Products Faster

Test-driven development (TDD) , as many of you might know, is one of the main, agile development techniques. The genius of TDD lies in increased quality of code, faster development resulting from greater programmer confidence, and improved bug detection (duh!).

Historically, web apps have been hard to autotest, and developers relied heavily on manual testing. But, certain parts such as standalone services and REST API can be and should be tested thoroughly by the TDD. At the same time, rich user interface (UI) / user experience (UX) can be tested with headless browsers such as PhantomJS.

Continue reading “How To Use Mocha With Node.js For Test-Driven Development to Avoid Pain and Ship Products Faster”

CoffeeScript: The Good Parts-Write Better JavaScript

I’ve published a new short course on CoffeeScript. The course will teach you major benefits of using CoffeeScript to write better JavaScript code for both browser and server.

You can save 66% off and get this course for only $3 with the code “wal”, or by clicking this link —>>> https://www.udemy.com/coffeescript/?couponCode=wal.

As always, the course has some bonus content. More information and preview is available as well.

Pro Express.js Q&A (Recording)

Last week, I did a live Q&A session for people who bought my new book Pro Express.js, but you can watch the recording here. Click on the apps icon (next to the ? icon), and then click on the Q&A button to see the questions. If you haven’t bought Pro Express.js, then you can do it on Amazon.com… and start mastering the framework for you Node.js web development.

PS: You can also watch the session on YouTube, but I recommend Google +.

Here is the summary of questions and answers which you can also get in a PDF —>>> Pro Express.js Q&A, or read below.

Continue reading “Pro Express.js Q&A (Recording)”

URL Parameters and Routing in Express.js

TL;DR: This post is about URL parameters and routing in Express.js, and it’s an excerpt (Chapter 6) from my new book Pro Express.js: Master Express.js—The Node.js Framework For Your Web Development. The book was released this week (~December 24, 2014), but we have a great limited-time offer for you which will be announced on Sunday, December 28, 2014 on Webapplog.com. This post is the last post in the series of excerpts from Pro Express.js with other posts as follow: Error Handling and Running an Express.js App, Express.js Security Tips, LoopBack 101: Express.js on Steroids, Sails.js 101 and Secret Express.js Settings.

To review, the typical structure of an Express.js app fig(which is usually a server.js or app.js file) roughly consists of these parts, in the order shown:

  1. Dependencies : A set of statements to import dependencies

  2. Instantiations : A set of statements to create objects

  3. Configurations : A set of statements to configure system and custom settings

  4. Middleware : A set of statements that is executed for every incoming request

  5. Routes : A set of statements that defines server routes, endpoints, and pages

  6. Bootup : A set of statements that starts the server and makes it listen on a specific port for incoming requests

This chapter covers the fifth category, routes and the URL parameters that we define in routes. These parameters, along with the app.param() middleware, are essential because they allow the application to access information passed from the client in the URLs (e.g., books/proexpressjs). This is the most common convention for REST APIs. For example, the http://hackhall.com/api/posts/521eb002d00c970200000003 route will use the value of 521eb002d00c970200000003 as the post ID.

Parameters are values passed in a query string of a URL of the request. If we didn’t have Express.js or a similar library, and had to use just the core Node.js modules, we’d have to extract parameters from an HTTP.request object via some require('querystring').parse(url) or require('url').parse(url, true) function “trickery.”

Let’s look closer at how to define a certain rule or logic for a particular URL parameter.

Continue reading “URL Parameters and Routing in Express.js”

LoopBack 101: Express.js on Steroids

LoopBack is a comprehensive Node.js web framework with a rich command-line scaffolding and a web API explorer: strongloop.com/node-js/loopback. The framework is maintained by StrongLoop which is also the gate-keeper of Express.js.

This concise tutorial will illustrate how to get started with LoopBack and the common traits between LoopBack and Express.js. This text is from my new book Pro Express.js by Apress which you can already start reading in Apress Alpha or pre-order on Amazon.com and other bookstores.

Continue reading “LoopBack 101: Express.js on Steroids”

Azat Mardan on NodeJS and Express Interview at QConNY 2014

Here’s my interview with Brian Rinaldi of ModernWeb on NodeJS and Express at QConNY 2014 where I spoke about CoffeeScript. The inverview is 13 minutes long and discusses some controversial topics and my traditionally published book Practical Node.js.

Continue reading “Azat Mardan on NodeJS and Express Interview at QConNY 2014”

MongoUI: Real-Time MongoDB Admin Web Interface (a la phpMyAdmin in Node.js)

MongoUI is a real-time web interface for Node.js and MongoDB written with DerbyJS—a real-time full-stack web framework. It’s a app that can be run locally and on the server. Similarly, you can view and manipulate data in a local or remote database. The MongoUI project is in beta so use caution, and please contribute your feedback.

MongoUI on NPM: https://www.npmjs.org/package/mongoui

MongoUI on GitHub: https://github.com/azat-co/mongoui

MongoUI description (this page): http://webapplog.com/mongoui

MongoUI features include:

  • Switch databases and collections
  • Search by field value (string, number, ObjectId)
  • Save search / filter results as a bookmark (each URL has a query)
  • Edit any fields’ values in a real-time editor
  • Get raw JSON objects

Here’s a one-and-a-half-minute video that shows filtering, editing, and switching collections:

Direct link to the YouTube video: http://youtu.be/l8Rfpow0f9A.

Continue reading “MongoUI: Real-Time MongoDB Admin Web Interface (a la phpMyAdmin in Node.js)”

CoffeeScript: The Good Parts

It’s not a secret that the topic of CoffeeScript is controversial to say the least. Many reputable JavaScript and Node.js developers just hate CoffeeScript, but there are lessons we can all learn from its good parts! However, many developers just won’t go back to plain JavaScript after building something relatively serious with CoffeeScript.

Continue reading “CoffeeScript: The Good Parts”

Introduction to OAuth with Node.js and Online Subscription—RELEASED!

The much-needed Introduction to OAuth with Node.js mini-book is released!

Introduction to OAuth with Node.js
Introduction to OAuth with Node.js: Twitter API OAuth 1.0, OAuth 2.0, OAuth Echo, Everyauth and OAuth 2.0 Server Examples

Get your PDF, EPUB, MOBI copy here –> gum.co/hRyc
or sign up for Node.js and JavaScript Mastery Online here.

The online bundle has five (5!) books. Here’s the list of available books. It’s a $50+ value for only $4.87/mo.

Node.js and JavaScript Mastery Online: Colored code examples—paste into your projects!
Node.js and JavaScript Mastery Online: Colored code examples—paste into your projects!

If you read all the books in less than a month—great! Just cancel the subscription. But most readers prefer to keep it just so they have a handy reference when they need it.

The Introduction to OAuth book includes:

  • OAuth 1.0
  • OAuth Echo
  • OAuth 2.0
  • OAuth 1.0 Sign in with Everyauth
  • OAuth 2.0 Server

A typical modern web applications has to communicate with other services. Even if it’s your own service or application. This is usually done via an open standard for authorization or OAuth. Therefore, the ability to use OAuth in your work is paramount!

There are standards, specifications and fancy diagrams, and it’s useful to read them as the first step. However, developers often need hands-on experience to acquire the full understanding and confidence.

Introduction to OAuth in Node.js is a concise practical book that will help you to get started with OAuth 1.0, 2.0, Echo and implement a Sign in with Node.js using Twitter API (and hopefully any other) authentication.

We’ll go through the three main authentication methods utilizing minimalistic oauth module to explain basics, then use extensive everyauth with an Express.js app.

Get your PDF, EPUB, MOBI copy here –> gum.co/hRyc
or sign up for Node.js and JavaScript Mastery Online here.

Intro to OAuth with Node.js: OAuth 1.0 (One-Legged)

This text is part of Introduction to OAuth with Node.js mini-book which is available at gum.co/hRyc.

Introduction to OAuth with Node.js
Introduction to OAuth with Node.js: Twitter API OAuth 1.0, OAuth 2.0, OAuth Echo, Everyauth and OAuth 2.0 Server Examples

Let’s start with good old OAuth 1.0. The way it usually works is as follows:

  1. For the first time, when we authorize a user to use our app, we need to perform extra work and obtain access token and secret (three-legged).
  2. You store these values for each user in your application.
  3. Then, on subsequent requests, things become much simpler. We construct auth headers and make HTTP requests (one-legged).

Continue reading “Intro to OAuth with Node.js: OAuth 1.0 (One-Legged)”

CoffeeScript FUNdamentals: The Better JavaScript

Disclaimer: This text is a part of the JavaScript and Node FUNdamentals: A Collection of Essential Basics ebook which is available now for free. However, upon the book’s completion it’ll be priced at $2.99. The book is 80% done as of this writing. The formats available: PDF, EPUB and Kindle. If you would like to participate in the writing process by providing your feedback and future topics, fill this short Future Topics and Feedback form.

Continue reading “CoffeeScript FUNdamentals: The Better JavaScript”

Practical Node.js TOC

As the Apress team of technical reviewers and copy editors and I make progress on the Practical Node.js manuscript, the date of the publication approaches fast. Last time I checked it was June 2014.

Practical Node.js: Building Real-world Scalable Web Apps
Practical Node.js: Building Real-world Scalable Web Apps

Many people ask me: how is the process compared to self-publishing? Is it worth the hassle?

So far, I can say only good things about my editors and the process of traditional publishing itself. I’m impressed about so many things I’ve already learned about structuring and technical writing. I feel like it enormously improved my style. There is more on this in my new meta book&resource ProgWriter.

As a sneak peek, here’s the tentative Table of Contents for the Practical Node.js book:

  1. Setting up Node.js and Other Essentials
  2. Using Express.js to Create Node.js Web Apps
  3. TDD and BDD for Node.js with Mocha
  4. Template Engines: Jade and Handlebars
  5. Persistence with MongoDB and Mongoskin
  6. Using Sessions and OAuth to Authorize and Authenticate Users in Node.js Apps
  7. Boosting Your Node.js Data with the Mongoose ORM Library
  8. Building Node.js REST API Servers with Express.js and Hapi
  9. Real-time Apps with WebSockets, Socket.IO and DerbyJS
  10. Getting Node.js Apps Production Ready
  11. Deploying Node.js Apps
  12. Publishing Node.js Modules and Contributing to Open Source

The good thing is that people who want to get the book first don’t have to wait ’til the book is released. They can pre-order the book on Amazon, or even better get access to the alpha version at Apress!

The alpha version will be release chapter by chapter starting in the next few weeks!

Express.js 4, Node.js and MongoDB REST API Tutorial

Usually good things don’t stay the same, so our tutorial on building a JSON REST API server with Node.js and MongoDB using Mongoskin and Express.js, and testing it with Mocha and Superagent, has became a bit outdated with the new Express.js 4 version release. Here’s a brand new, revisited tutorial for Express.js 4, Node.js and MongoDB (Mongoskin) free-JSON RESTful API server.

The code for this new tutorial is available at github.com/azat-co/rest-api-express (master branch). The old tutorial’s code for Express 3.x, is still working and in the express3 branch.

Express.js 4 and MongoDB REST API Tutorial consists of these parts:

  1. Node.js and MongoDB REST API Overview
  2. REST API Tests with Mocha and Superagent
  3. NPM-ing Node.js Server Dependencies
  4. Express.js 4.x Middleware Caveat
  5. Express.js and MongoDB (Mongoskin) Implementation
  6. Running The Express.js 4 App and Testing MongoDB Data with Mocha
  7. Conclusion and Further Express.js and Node.js Reading

Instead of TL;DR:

If you’re only interested in a working code from the repository and know what to do, here are brief instructions on how to download and run the REST API server:

$ git clone git@github.com:azat-co/rest-api-express.git
$ npm install
$ node express.js

Start MongoDB with $ mongod. Then, in a new terminal window run the Mocha tests:

$ mocha express.test.js

Or, if you don’t have mocha installed globally:

$ ./node_modules/mocha/bin/mocha express.test.js

Node.js and MongoDB REST API Overview

This Node.js, Express.js and MongoDB (Mongoskin) tutorial will walk you through writing the test using the Mocha and Super Agent libraries. This is needed for a test-driven development building of a Node.js free JSON REST API server.

The server application itself will utilize Express.js 4.x framework and Mongoskin library for MongoDB. In this REST API server, we’ll perform create, read, update and delete (CRUD) operations and harness Express.js middleware concept with app.param() and app.use() methods.

First of all, make sure you have MongoDB installed. You can follow the steps on the official website.

We’ll be using the following versions of libraries:

  • express: ~4.1.1
  • body-parser: ~1.0.2
  • mongoskin: ~1.4.1
  • expect.js: ~0.3.1
  • mocha: ~1.18.2
  • superagent: ~0.17.0

If you try to attempt to use later or older versions the code might not work. :-(

Continue reading “Express.js 4, Node.js and MongoDB REST API Tutorial”

CoffeeScript Quirks

CoffeeScript is a solution without the problem.

— Unknown ironic source.

CoffeeScript is awesome, until it’s totally confusing, and it’s illogical, which can lead to unexpected and subtle bugs. If you’re one of the CoffeeScript haters please skip this post; for others, I’ll share a few notes on the CS quirks that I’ve observed.

For example, let’s say we have a counter and need to assign a value of index subtracted by one to it:

numberOfRadios = index -1

But the line above is not the same as:

numberOfRadios = index - 1

Did you notice that there’s a space after the minus sign in the second example? It took me awhile to track down this type of bug. The reason for this behavior is that the first line will be converted by the compiler to the function invocation and that is probably not what you wanted.

Try the minus one snippet on CoffeeScript.org. It outputs the following JavaScript code:

var numberOfRadios;

numberOfRadios = index(-1);

numberOfRadios = index - 1;

Another pitfall, that leads to writing despondently inconsistent code (by us developers), is caused by the fact that parentheses are optional for function calls.

This example involves if conditions in which we want to compare the value of the expression model.get() or the operand typeof to some strings:

a() if @model.get 'groupType' is 'radioGroupTabs'
a() if typeof @model.get 'condition' is 'function'

CoffeeScript is treating the entire thing as an argument and the results are pathetic. Duh. ;-( Here is the native JavaScript code:

if (this.model.get('groupType' === 'radioGroupTabs')) {
  a();
}

if (typeof this.model.get('condition' === 'function')) {
  a();
}

Placing parens over the function still does us no good. Look at this CoffeeScript code:

a() if @model.get ('groupType') is 'radioGroupTabs'

And its JavaScript output:

if (this.model.get('groupType' === 'radioGroupTabs')) {
  a();
}

The workaround involves using () around function calls, or flipping the order in the if statement so that the function invocation is the last bit of code in the if statement:

a() if (typeof @model.get 'condition') is 'function'
a() if 'function' is typeof @model.get 'condition'
a() if (@model.get 'groupType') is 'radioGroupTabs'
a() if 'radioGroupTabs' is  @model.get ('groupType')

The code above compiles to what we wanted originally:

if ((typeof this.model.get('condition')) === 'function') {
  a();
}

if ('function' === typeof this.model.get('condition')) {
  a();
}

if ((this.model.get('groupType')) === 'radioGroupTabs') {
  a();
}

if ('radioGroupTabs' === this.model.get('groupType')) {
  a();

Is it all good now? Not really, because I personally think this approach leads to inconsistencies: parts of CoffeeScript code that must have parentheses, while in other places they are optional.

Try these if conditon snippets yourself on CoffeeScript.org.

The next note explains the most common beginner’s mistake in CoffeeScript; that is to use an a instead of an a() for function calls. However, super inside of a class, must be called without parentheses in order to pass the arguments to it.

Moving on to the single hash (#) comments which are just skipped over by CoffeeScript. Again, this can lead to unexpected consequences.

For example, a straightforward if statement has a few lines of code:

unless A 
  b()
  blah blah

But if we comment out all of the lines inside of if, the whole thing will fail miserably at the compilation step (at least thank you for that, CoffeeScript!):

unless A 
  # b()
  # blah blah

Just by adding an empty else we can mitigate the failure:

unless A 
  # b()
  # blah blah
else


c() # the code continues here

Try this snippet yourself on CoffeeScript.org

Last but not least, there is another CoffeeScript pitfall related to jQuery events that don’t propagate when the event handler returns false. Of course, CoffeeScript philosophy makes every function an expression (the last statement is evaluated if there is no return statement present).

b = ()->
  false # usually this result is less obvious and buried deep down in code
$a = $ 'input'
$a.click ()->
  console.log 'this happens all right'
  b()

$a.parent().click ()->
  console.log('this never happened')

Of course, in real life the b() function is not so obvious and it’s buried somewhere deep within Backbone and Angular model methods. And the event isn’t propagating up the DOM tree (return false). Therefore, we’ve lost the second event handler without even realizing t. Buyers beware of this elusiveness! :-)

Try the event propagation bug yourself on CoffeeScript.org

This is the end of my list. If you know of any additional CoffeeScript idiosyncrasies, please send them my way. :-)

Further CoffeeScript reading:

Breaking Bad (Loops in JavaScript Libraries)

JavaScript Libraries are important (e.g., jQuery, Lo-Dash, Underscore), but in the case of asynchronous loops (`forEach` and `each`) they create a lot of confusion… Lo-Dash is not equal to Underscore, unless a special underscore-compatible version is being used.

It was sort of a surprise for me when I discovered inconsistencies in the most popular JavaScript libraries in how they handle their each and forEach loops. This post compares:

  • forEach Loop in Native JavaScript
  • each Loop in Lo-Dash
  • each Loop in jQuery
  • each Loop in Underscore.js
  • forEach Loop in Underscore.js

forEach Loop in Native JavaScript

JavaScript Libraries are important (e.g., jQuery, Lo-Dash, Underscore), but in the case of functional loops (forEach and each) they create a lot of confusion (for loop can be broken with ‘break’). Let’s inspect the example of native JavaScript code for the forEach method:

[1,2].forEach(function(v){
  alert(v);
  return false;
})

This will display us two alert boxes. Try the native JavaScript code yourself in JSFiddle.

This is an expected behavior in most cases because with each iteration we invoke a new function. Unlike the for (var i=0; i<arr.length; i++) {} code that has no function/iterators.

Continue reading “Breaking Bad (Loops in JavaScript Libraries)”