Full Stack JavaScript

My new book Full Stack JavaScript (my 4th traditionally-published book) comes with a series of screencast videos for better immersion in a wonderful and mesmerizing world of Node.js, Backbone and MongoDB. It’s a one thing to read through the text and another to follow up with dynamic videos which walk you through the book’s projects.

Full Stack JavaScript
Full Stack JavaScript

The videos and the source code are open source, meaning they are publicly available. Therefore, you don’t have to buy a book—you can just watch the 14 videos on YouTube (playlist) and go through the code on GitHub (repository).

Continue reading “Full Stack JavaScript”

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)”

Express.js and Mongoose Example: Building HackHall

Note: This text is a part of the Express.js Guide: The Comprehensive Book on Express.js.

The HackHall project was written using Backbone.js and Underscore for the front-end app, and Express.js, MongoDB via Mongoose for the back-end REST API server.

Continue reading “Express.js and Mongoose Example: Building HackHall”

The Release of Express.js Guide: The Comprehensive Book on Express.js

After weeks of writing and editing, Azat and his team are happy to announce the release of Express.js Guide: The Most Popular Node.js Framework Manual! The book is very approachable and suitable for beginners. If someone wants to save time searching the web and learn the best practices from the trenches, Express.js Guide is the book that has everything: Express.js API reference, quick start guides, 20+ meticulously explained examples and tutorials on over 270 pages with more than 60 illustrations.

Express.js is a de facto standard of Node.js development and the most popular NPM library as of today! However, as with any framework, sometimes the learning curve is steep. At HackReactor, I often asked the same questions about code organization, authentication, database connections and deployment.

Continue reading “The Release of Express.js Guide: The Comprehensive Book on Express.js”

Todo App with Express.js/Node.js and MongoDB

Todo apps are considered to be quintessential in showcasing frameworks akin to famous Todomvc.com for front-end JavaScript frameworks. In this example, we’ll use Jade, forms, LESS, AJAX/XHR and CSRF.

Note: This tutorial is a part of Express.js Guide: The Comprehensive Book on Express.js.

Todo apps are considered to be quintessential in showcasing frameworks akin to famous Todomvc.com for front-end JavaScript frameworks. In this example, we’ll use Jade, forms, LESS, AJAX/XHR and CSRF.

In our Todo app, we’ll intentionally not use Backbone.js or Angular to demonstrate how to build traditional websites with the use of forms and redirects. In addition to that, we’ll explain how to plug-in CSRF and LESS.

Example: All the source code is in the github.com/azat-co/todo-express for your convenience.

Continue reading “Todo App with Express.js/Node.js and MongoDB”

Tutorial: Node.js and MongoDB JSON REST API server with Mongoskin and Express.js

Tutorial: building a JSON REST API server with Node.js and MongoDB using Mongoskin and Express.js utilizing Mocha and Super Agent for BDD/TDD.

Update3: Expess 4 version of this tutorial is available at Express.js 4, Node.js and MongoDB REST API Tutorial, and github.com/azat-co/rest-api-express (master branch). This tutorial will work with Express 3.x.

Update2: “Mongoskin removed ‘db.collection.id’ and added some actionById methods” from this pull request with this code changes. To use the code in this post, just install an older version of Mongoskin (0.5.0?). The code in the GitHub will work with Mongoskin 1.3.20.

Update2: “Mongoskin removed ‘db.collection.id’ and added some actionById methods” from this pull request with this code changes. To use the code in this post, just install an older version of Mongoskin (0.5.0?)

Update: use the enhanced code from this repository github.com/azat-co/rest-api-express (express3 branch).

Note: This text is a part of Express.js Guide: The Comprehensive Book on Express.js.

This tutorial will walk you through writing test using the Mocha and Super Agent libraries and then use them in a test-driven development manner to build a Node.js free JSON REST API server utilizing Express.js 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.

Continue reading “Tutorial: Node.js and MongoDB JSON REST API server with Mongoskin and Express.js”

Rapid Prototyping with JS: Agile JavaScript Development is done with v0.5 (1.0RC)!

This is a release candidate for 1.0 version which is going to be available to public in print. Page count has increase from 151 to 211 pages (PDF), which include the following updates:

More digestible (smaller) code examples with better comments
Express.js middleware section with an example
Express.js + MongoDB REST API server section with an example
Derby section with an example
Grammar and typo fixes
Illustrations
Summaries in the beginning of each chapter
Code examples formatting fixes

Rapid Prototyping with JS: Agile JavaScript Development
Rapid Prototyping with JS: Agile JavaScript Development

This is a release candidate for 1.0 version which is going to be available to public in print. Page count has increase from 151 to 211 pages (PDF), which include the following updates:

  • More digestible (smaller) code examples with better comments
  • Express.js middleware section with an example
  • Express.js + MongoDB REST API server section with an example
  • Derby section with an example
  • Grammar and typo fixes
  • Illustrations
  • Summaries in the beginning of each chapter
  • Code examples formatting fixes

Download a free chapter Intro to Backbone.js or full PDF, ePub or Mobi copy at LeanPub.

Rapid Prototyping with JS touched topics such as:

  • jQuery
  • AJAX
  • CSS and LESS
  • JSON and BSON
  • Twitter Bootstrap
  • Node.js
  • MongoDB
  • Parse.com
  • Agile methodologies
  • Git
  • Heroku, MongoHQ and Windows Azure
  • REST API
  • Backbone.js
  • AMD and Require.js
  • Express.js
  • Monk
  • Derby

If you need in-depth knowledge or references, they are usually one click or one Google search away.

Practical aspect included building multiple versions of the Message Board app:

  • jQuery + Parse.com JS REST API
  • Backbone and Parse.com JS SDK
  • Backbone and Node.js
  • Backbone and Node.js + MongoDB

The Message Board application has all the foundation of a typical web/mobile application: fetching data, displaying it, submitting new data. Other examples include:

  • jQuery + Twitter RESP API “Tweet Analyzer”
  • Parse.com “Save John”
  • Node.js “Hello World”
  • MongoDB “Print Collections”
  • Derby + Express “Hello World”
  • Backbone.js “Hello World”
  • Backbone.js “Apple Database”
  • Monk + Expres.js “REST API Server”

Oh My JS: The Best JavaScript Articles (https://leanpub.com/ohmyjs/) is in the works!

Nested Objects in Mongoose

There is a certain magic in ORMs like Mongoose. I learned it the hard way (as usual!), when I was trying to iterate over nested object’s properties…

There is a certain magic in ORMs like Mongoose. I learned it the hard way (as usual!), when I was trying to iterate over nested object’s properties. For example, here is a schema with a nested object features defines like this:

var User = module.exports = new Schema({
  features: { 
    realtime_updates: {
      type: Boolean
    },
    storylock: {
      type: Boolean
    },
    custom_embed_style: {
      type: Boolean
    },
    private_stories: {
      type: Boolean
    },
    headerless_embed:{
      type: Boolean
    }
};

Let’s say I want to overwrite object features_enabled with these properties:

if (this.features) { 
  for (var k in this.features) {
    features_enabled[k] = this.features[k];
  }
}
console.log(features_enabled)
return features_enabled;

Not so fast, I was getting a lot of system properties specific to Mongoose. Instead we need to use toObject(), e.g.:

if (this.features.toObject()) { 
  for (var k in this.features.toObject()) {
    console.log('!',k)
    features_enabled[k] = this.features.toObject()[k];
  }
}

Remember rule number one, computer is always right. If we think that it’s wrong — look up the rule number one. :-)

Intro to Express.js: Simple REST API app with Monk and MongoDB

After looking at Google Analytics stats I’ve realized that there is a demand for short Node.js tutorial and quick start guides. This is an introduction to probably the most popular (as of April 2013) Node.js framework Express.js.

Why?

After looking at Google Analytics stats I’ve realized that there is a demand for short Node.js tutorial and quick start guides. This is an introduction to probably the most popular (as of April 2013) Node.js framework Express.js.

Express.js — Node.js framework
Express.js — Node.js framework

mongoui

This app is a start of mongoui project. A phpMyAdmin counterpart for MongoDB written in Node.js. The goal is to provide a module with a nice web admin user interface. It will be something like Parse.com, Firebase.com, MongoHQ or MongoLab has but without trying it to any particular service. Why do we have to type db.users.findOne({'_id':ObjectId('...')}) any time we want to look up the user information? The alternative of MongoHub mac app is nice (and free) but clunky to use and not web based.

REST API app with Express.js and Monk

Ruby enthusiasts like to compare Express to Sinatra framework. It’s similarly flexible in the way how developers can build there apps. Application routes are set up in a similar manner, i.e., app.get('/products/:id', showProduct);. Currently Express.js is at version number 3.1. In addition to Express we’ll use Monk module.

We’ll use Node Package Manager which is usually come with a Node.js installation. If you don’t have it already you can get it at npmjs.org.

Create a new folder and NPM configuration file, package.json, in it with the following content:

{
  "name": "mongoui",
  "version": "0.0.1",
  "engines": {
    "node": ">= v0.6"
  },
  "dependencies": {
    "mongodb":"1.2.14",
    "monk": "0.7.1",
    "express": "3.1.0"
  }
}

Now run npm install to download and install modules into node_module folder. If everything went okay you’ll see bunch of folders in node_modules folders. All the code for our application will be in one file, index.js, to keep it simple stupid:

var mongo = require('mongodb');
var express = require('express');
var monk = require('monk');
var db =  monk('localhost:27017/test');
var app = new express();

app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
  db.driver.admin.listDatabases(function(e,dbs){
      res.json(dbs);
  });
});
app.get('/collections',function(req,res){
  db.driver.collectionNames(function(e,names){
    res.json(names);
  })
});
app.get('/collections/:name',function(req,res){
  var collection = db.get(req.params.name);
  collection.find({},{limit:20},function(e,docs){
    res.json(docs);
  })
});
app.listen(3000)

Let break down the code piece by piece. Module declaration:

var mongo = require('mongodb');
var express = require('express');
var monk = require('monk');

Database and Express application instantiation:

var db =  monk('localhost:27017/test');
var app = new express();

Tell Express application to load and server static files (if there any) from public folder:

app.use(express.static(__dirname + '/public'));

Home page, a.k.a. root route, set up:

app.get('/',function(req,res){
  db.driver.admin.listDatabases(function(e,dbs){
      res.json(dbs);
  });
});

get() function just takes two parameters: string and function. The string can have slashes and colons, for example product/:id. The function must have two parapemets request and response. Request has all the information like query string parameters, session, headers and response is an object to with we output the results. In this case we do it by calling res.json() function. db.driver.admin.listDatabases() as you might guess give us a list of databases in async manner.

Two other routes are set up in a similar manner with get() function:

app.get('/collections',function(req,res){
  db.driver.collectionNames(function(e,names){
    res.json(names);
  })
});
app.get('/collections/:name',function(req,res){
  var collection = db.get(req.params.name);
  collection.find({},{limit:20},function(e,docs){
    res.json(docs);
  })
});

Express conveniently supports other HTTP verbs like post and update. In the case of setting up a post route we write this:

app.post('product/:id',function(req,res) {...});

Express also has support for middeware. Middleware is just a request function handler with three parameters: request, response, and next. For example:

app.post('product/:id', authenticateUser, validateProduct, addProduct);

function authenticateUser(req,res, next) {
  //check req.session for authentication
  next();
}

function validateProduct (req, res, next) {
   //validate submitted data
   next();
}

function addProduct (req, res) {
  //save data to database
}

validateProduct and authenticateProduct are middleware. They are usually put into separate file (or files) in a big projects.

Another way to set up middle ware in Express application is to use use() function. For example earlier we did this for static assets:

app.use(express.static(__dirname + '/public'));

We can also do it for error handlers:

app.use(errorHandler);

Assuming you have mongoDB installed this app will connect to it (localhost:27017) and display collection name and items in collections. To start mongo server:

$ mongod

to run app (keep the mongod terminal window open):

$ node .

or

$ node index.js

To see the app working, open http://localhost:3000 in Chrome with JSONViewer extension (to render JSON nicely).

Tom Hanks' The Polar Express
Tom Hanks’ The Polar Express

MongoDB migration with Node and Monk

Recently one of our top users complained that their Storify account is unaccessible. We’ve checked the production database and it appeared to be that the account might have been compromised and maliciously deleted by somebody using user’s account credentials. Thanks for a great MongoHQ service we had a backup database in less than 15 minutes.

Recently one of our top users complained that their Storify account was unaccessible. We’ve checked the production database and it appeares to be that the account might have been compromised and maliciously deleted by somebody using user’s account credentials. Thanks to a great MongoHQ service, we had a backup database in less than 15 minutes.
There were two options to proceed with the migration:

  1. Mongo shell script
  2. Node.js program

Because Storify user account deletion involves deletion of all related objects — identities, relationships (followers, subscriptions), likes, stories — we’ve decided to proceed with the latter option. It worked perfectly, and here is a simplified version which you can use as a boilerplate for MongoDB migration (also at gist.github.com/4516139).

Restoring MongoDB Records
Restoring MongoDB Records

Let’s load all the modules we need: Monk, Progress, Async, and MongoDB:

var async = require('async');
var ProgressBar = require('progress');
var monk = require('monk');
var ObjectId=require('mongodb').ObjectID;

By the way, made by LeanBoost, Monk is a tiny layer that provides simple yet substantial usability improvements for MongoDB usage within Node.JS.

Monk takes connection string in the following format:

username:password@dbhost:port/database

So we can create the following objects:

var dest = monk('localhost:27017/storify_localhost');
var backup = monk('localhost:27017/storify_backup');

We need to know the object ID which we want to restore:

var userId = ObjectId(YOUR-OBJECT-ID); 

This is a handy restore function which we can reuse to restore objects from related collections by specifying query (for more on MongoDB queries go to post Querying 20M-Record MongoDB Collection. To call it, just pass a name of the collection as a string, e.g., "stories" and a query which associates objects from this collection with your main object, e.g., {userId:user.id}. The progress bar is needed to show us nice visuals in the terminal.

var restore = function(collection, query, callback){
  console.info('restoring from ' + collection);
  var q = query;
  backup.get(collection).count(q, function(e, n) {
    console.log('found '+n+' '+collection);
    if (e) console.error(e);
    var bar = new ProgressBar('[:bar] :current/:total :percent :etas', { total: n-1, width: 40 })
    var tick = function(e) {
      if (e) {
        console.error(e);
        bar.tick();
      }
      else {
        bar.tick();
      }
      if (bar.complete) {
        console.log();
        console.log('restoring '+collection+' is completed');
        callback();                
      }
    };
    if (n>0){
      console.log('adding '+ n+ ' '+collection);
      backup.get(collection).find(q, { stream: true }).each(function(element) {
        dest.get(collection).insert(element, tick);
      });        
    } else {
      callback();
    }
  });
}

Now we can use async to call the restore function mentioned above:

async.series({
  restoreUser: function(callback){   // import user element
    backup.get('users').find({_id:userId}, { stream: true, limit: 1 }).each(function(user) {
      dest.get('users').insert(user, function(e){
        if (e) {
          console.log(e);
        }
        else {
          console.log('resored user: '+ user.username);
        }
        callback();
      });
    });
  },

  restoreIdentity: function(callback){  
    restore('identities',{
      userid:userId
    }, callback);
  },

  restoreStories: function(callback){
    restore('stories', {authorid:userId}, callback);
  }

  }, function(e) {
  console.log();
  console.log('restoring is completed!');
  process.exit(1);
});

The full code is available at gist.github.com/4516139 and here:

var async = require('async');
var ProgressBar = require('progress');
var monk = require('monk');
var ms = require('ms');
var ObjectId=require('mongodb').ObjectID;

var dest = monk('localhost:27017/storify_localhost');
var backup = monk('localhost:27017/storify_backup');

var userId = ObjectId(YOUR-OBJECT-ID); // monk should have auto casting but we need it for queries

var restore = function(collection, query, callback){
  console.info('restoring from ' + collection);
  var q = query;
  backup.get(collection).count(q, function(e, n) {
    console.log('found '+n+' '+collection);
    if (e) console.error(e);
    var bar = new ProgressBar('[:bar] :current/:total :percent :etas', { total: n-1, width: 40 })
    var tick = function(e) {
      if (e) {
        console.error(e);
        bar.tick();
      }
      else {
        bar.tick();
      }
      if (bar.complete) {
        console.log();
        console.log('restoring '+collection+' is completed');
        callback();                
      }
    };
    if (n>0){
      console.log('adding '+ n+ ' '+collection);
      backup.get(collection).find(q, { stream: true }).each(function(element) {
        dest.get(collection).insert(element, tick);
      });        
    } else {
      callback();
    }
  });
}

async.series({
  restoreUser: function(callback){   // import user element
    backup.get('users').find({_id:userId}, { stream: true, limit: 1 }).each(function(user) {
      dest.get('users').insert(user, function(e){
        if (e) {
          console.log(e);
        }
        else {
          console.log('resored user: '+ user.username);
        }
        callback();
      });
    });
  },

  restoreIdentity: function(callback){  
    restore('identities',{
      userid:userId
    }, callback);
  },

  restoreStories: function(callback){
    restore('stories', {authorid:userId}, callback);
  }

  }, function(e) {
  console.log();
  console.log('restoring is completed!');
  process.exit(1);
});
           

To launch it, run npm install/update and change hard-coded database values.

Querying 20M-Record MongoDB Collection

Storify saves a lot of meta data about social elements: tweets, Facebook status updates, blog posts, news articles, etc. MongoDB is great for storing such unstructured data but last week I had to fix some inconsistency in 20-million-record Elements collection.

Storify saves a lot of meta data about social elements: tweets, Facebook status updates, blog posts, news articles, etc. MongoDB is great for storing such unstructured data but last week I had to fix some inconsistency in 20-million-record Elements collection.

The script was simple: find elements, see if there are no dependencies, delete orphan elements, neveretheless it was timing out or just becoming unresponsive. After a few hours of running different modifications I came up with the working solution.

Here are some of the suggestions when dealing with big collections on Node.js + MongoDB stack:

Befriend Shell

Interactive shell, or mongo, is a good place to start. To launch it, just type mongo in your terminal window:

$ mongo

Assuming you have correct paths set-up during your MongoDB installation, the command will start the shell and present angle brace.

>

Use JS files

To execute JavaScript file in a Mongo shell run:

$ mongo fix.js --shell

Queries look the same:

db.elements.find({...}).limit(10).forEach(printjson);

To output results use:

print();

or

printjson();

To connect to a database:

db = connect("<host>:<port>/<dbname>")

Break Down

Separate your query into a few scripts with smaller queries. You can output each script to a file (as JSON or CSV) and then look at the output and see if your script is doing what it is actually supposed to do.

To execute JavaScript file (fix.js) and output results into another file (fix.txt) instead of the screen, use:

$ mongo fix.js > fix.txt --shell

or

$ mongo --quiet fix.js > fix.txt --shell

Check count()

Simply run count() to see the number of elements in the collection:

 db.collection.count();

or a cursor:

 db.collection.find({…}).count();

Use limit()

You can apply limit() function to your cursor without modifying anything else in a script to test the output without spending too much time waiting for the whole result.

For example:

 db.find({…}).limit(10).forEach(function() {…});

or

 db.find({…}).limit(1).forEach(function() {…});

is better than using:

 db.findOne({…})

because findOne() returns single document while find() and limit() still returns a cursor.

Hit Index

hint() index will allow you to manually use particular index:

 db.elemetns.find({…}).hint({active:1, status:1, slug:1});

Make sure you have actual indexes with ensureIndex():

 db.collection.ensureIndex({…})

Narrow Down

Use additional criteria such as $ne, $where, $in, e.g.:

db.elements.find({ $and:[{type:'link'}
  ,{"source.href":{$exists:true}}
  ,{'date.created':{$gt: new Date("November 30 2012")}}
  ,{$where: function () {
    if (this.meta&&this.data&&this.data&&this.data.link) {
      return this.meta.title!=this.data.link.title;
    } else {
      return false;
    }}} 
  , {'date.created': {$lt: new Date("December 2 2012")}}]}).forEach(function(e, index, array){
    print(e._id.str);
    });

Rapid Prototyping with JS is out!

Rapid Prototyping with JS is a hands-on book which introduces you to rapid software prototyping using the latest cutting-edge web and mobile technologies including NodeJS, MongoDB, BackboneJS, Twitter Bootstrap, LESS, jQuery, Parse.com, Heroku and others.

The Book is on LeanPub

Rapid Prototyping with JS is a hands-on book which introduces you to rapid software prototyping using the latest cutting-edge web and mobile technologies including NodeJS, MongoDB, BackboneJS, Twitter Bootstrap, LESS, jQuery, Parse.com, Heroku and others.

The book has 84 pages (in PDF format) or 13,616 words to be precise, step-by-step set-up, best practice advices, web development overview, 11 code examples (also available ready-to-go in GitHub repository azat-co/rpjs), flexible pricing ($9.99–19.99).

Order your copy of Rapid Prototyping with JS at LeanPub: leanpub.com/rapid-prototyping-with-js.

Rapid Prototyping with JS
Rapid Prototyping with JS: Learn how to build web and mobile apps using JavaScript and Node.js

LeanPub platform allows readers to receive infinite future updates (current version of the book is 0.3) and read the book in the most popular digital formats: PDF, ePub/iPad, MOBI/Kindle. The PDF version has footnote links which make it suitable for printing.

Download a free sample at samples.leanpub.com/rapid-prototyping-with-js-sample.pdf.

What Readers Say

Rapid Prototyping with JS is being successfully used at StartupMonthly as a training manual. Here are some of our trainees’ testimonials:

“Thanks a lot to all and special thanks to Azat and Yuri. I enjoyed it a lot and felt motivated to work hard to know these technologies.” — Shelly Arora

“Thanks for putting this workshop together this weekend… what we did with Bootstrap + Parse was really quick & awesome.” — Mariya Yao

“Thanks Yuri and all of you folks. It was a great session – very educative, and it certainly helped me brush up on my Javascript skills. Look forward to seeing/working with you in the future.” — Sam Sur

Who This Book is For

The book is designed for advanced-beginner and intermediate level web and mobile developers: somebody who has just started programming and somebody who is an expert in other languages like Ruby on Rails, PHP, and Java and wants to learn JavaScript and Node.js.

Rapid Prototyping with JS, as you can tell from the name, is about taking your idea to a functional prototype in the form of a web or a mobile application as fast as possible. This thinking adheres to the Lean Startup methodology. Therefore, this book would be more valuable to startup founders, but big companies’ employees might also find it useful, especially if they plan to add new skills to their resume.

Prerequisite

Mac OS X or UNIX/Linux systems are highly recommended for this book’s examples and for web development in general, although it’s still possible to hack your way on a Windows-based system.

Contents

Acknowledgment

Introduction

  1. Who This Book is For
  2. Prerequisite
  3. What to Expect
  4. Notation
  5. Web Basics: Hyper Text Markup Language, Cascading Style Sheets, JavaScript
  6. Agile Methodologies: Scrum, Test-Driven Development, Continuous Deployment, Paired Programming
  7. Node.js
  8. NoSQL and MongoDB
  9. Cloud Computing
  10. HTTP Requests and Responses
  11. RESTful API

Getting Started

  1. Development Folder
  2. Browsers
  3. IDEs and Text Editors
  4. Version Control Systems
  5. Local HTTP Servers
  6. Database: MongoDB
  7. Other Components: NodeJS, jQuery, LESS
  8. SSH Keys
  9. GitHub
  10. Windows Azure
  11. Heroku
  12. Cloud9

Building Front-End Application

  1. JSON
  2. AJAX
  3. Cross-Domain Calls
  4. jQuery
  5. Twitter Bootstrap
  6. LESS
  7. BackboneJS
  8. Example of using Twitter REST API and jQuery
  9. Parse.com
  10. Message Board with Parse.com
  11. Message Board with Parse.com: REST API and jQuery version
  12. Pushing to GitHub
  13. Deployment to Windows Azure
  14. Deployment to Heroku
  15. Message Board with Parse.com: JavaScript SDK and BackboneJS version
  16. Deploying Message Board to PaaS
  17. Enhancing Message Board
  18. Building Back-End Application

Building “Hello World” in NodeJS

  1. NodeJS Core Modules
  2. Node Package Manager
  3. Deploying “Hello World” to PaaS
  4. Deploying to Windows Azure
  5. Deploying to Heroku
  6. Message Board: Run-Time Memory version
  7. Test Case for Message Board
  8. MongoDB Shell
  9. MongoDB Native Driver
  10. MongoDB on Heroku: MongoHQ MongoHQ URL
  11. BSON
  12. Message Board: MongoDB version

Putting it All Together

  1. Different Domain Deployment
  2. Changing Endpoints
  3. Message Board Application
  4. Deployment
  5. Same Domain Deployment

Further Reading

About the Author

Order your copy of Rapid Prototyping with JS at LeanPub: leanpub.com/rapid-prototyping-with-js.

Pilot Rapid Prototyping with JavaScript and NodeJS Class

Traditional Computer Science education sucks big time when it comes to modern agile technologies like Ruby on Rails, Django, NodeJS, and NoSQL databases. Last time I checked, the maximum that was offered were classes in Web Design I, Web Design II and Photoshop Basics. WTF?! Don’t get me wrong. I have Master’s degree in Information Systems Technology and value fundamentals, but I was never taught anything up-to-date. There was some ASP, some C++, some SQL, but most of my learning I had to do on my own. Sure there are tons information online and in books, but not everybody has time, dedication, focus and self-discipline to master a new technical skill this way. Reading a book or watching a screencast is just not enough. The best learning comes from 25% books, 25% peer-to-peer communication and discussion, 25% student-to-teacher relationship; the last 25% is the time and practice on your own.

I saw a huge need for effective technical trainings and decided to validate my idea. I already had plenty of teaching experience from college years, during which I wrote my first textbook, had it published on a curriculum for my classmates a year later, and from teaching yoga classes. I needed a pilot class, so I approached startup accelerator and fund, StartupMonthly, and offered to develop and teach the “Rapid Prototyping with JavaScript and NodeJS” training.

I chose JavaScript and NodeJS because students will be able to use the same language both for front-end and back-end development. Their brains don’t have to switch thus saving time and speeding the learning process. NodeJS is becoming more and more popular due to its real-time support and I’m very passionate about this technology. The training runs over a long weekend, starting on Friday night with an optional Q&A session on setting up your environment. Then, we have two full days on Saturday and Sunday, making the course 16 hours total. This way, people who have full time jobs don’t have to take time off to attend. The class is very hands-on and, as much as possible, inline with the principles of Flipped Teaching.

Rapid Prototyping with JavaScript and NodeJS - Day 1
Day 1

The goal was not to make a profit. So we priced the training very aggressively twice or thrice lower than the market price of our competitors in order to attract students. The results were amazing! The goal was to sell at least 10 seats and we had 15 people in our first class! Big thanks to Yuri Rabinovich, killer StartupMonthly team and its vast network of people interested in technology :)

Rapid Prototyping with JavaScript and NodeJS - Day 2
Day 2

Then the hard work began. In a true spirit of lean startup methodology (hey, this is what we teach, right?) the manual had only a bare minimum of information and was tailored towards intermediate web and JavaScript developers. The majority was doing well, but I couldn’t say that for everyone. This was a good feedback for me, and helped to improve the manual by including many simple steps and additional terminal commands for deployment and Git.

Optimize but not too over optimize
“Optimize, but not over optimize”

Overall, students were tired, but happy with the number of new technologies they’ve tried. It was sort of a Chinese Buffet of Programming. You don’t have to try everything, you only pick what you want and indulge in it :) Here is the list of topics to give you an idea:

  • Agile, Continuous Deployment, TDD, Pair Programming
  • Basic front-end technologies: JavaScript, HTML, CSS
  • NodeJS and its advantages. Event driven programming.
  • MongoDB and Document Store and Key-Value concepts.
  • JSON, structure and examples.
  • Could computing. Cloud platforms: Windows Azure, Heroku.
  • Structure of HTTP Request and Response: headers, body, methods
  • RESTful API, examples and advantages.
  • Overview of HTML: structure, tags and syntax. Inclusion of CSS, JavaScript files/tags.
  • jQuery: AJAX, cross-domain calls and JSONP
  • Twitter Bootstrap: grid layout, form components, icons
  • LESS: mixins, variables and compilation.
  • BackboneJS: structure, events, view, sub-views, models, collections and event listeners and event binding.
  • Parse.com: plain REST API calls with jQuery ajax function and JavaScript SDK with Backbone compatible library.
  • Generating of SSH keys, configuring Git, GitHub, Heroku and Windows Azure for deployment.
  • Installation and basic configuration of NodeJS and MongoDB in local environment.
  • Deployment of NodeJS and MongoDB and static/front-end applications to PaaS cloud services like Windows Azure and Heroku with Git.
  • Building sample applications with NodeJS, jQuery, BackboneJS, Twitter Bootstrap, MongoDB, Parse.com and other tools/technologies. Deploying it to cloud services.
  • Building your own idea/prototype and presenting it. Deploying it to cloud services.
  • Practicing Paired Programming and Test-Driven Development techniques.
Next Billion-Dollar Idea
Next Billion-Dollar Idea

By the end of the weekend, we had 3 teams with 2 to 3 people in each. The teams built or started to build applications using their own ideas. One of them was a remake of Reddit with better UX/UI and the other was a service for angry ex-girlfriends to post (mostly negative I suspect) feedbacks on their ex-boyfriends :)

Here are some testimonials from the students:

“Thanks Yuri and all of you folks. It was a great session – very educative, and it certainly helped me brush up on my Javascript skills. Look forward to seeing/working with you in the future” – Sam Sur.

“Thanks for putting this workshop together this weekend… what we did with Bootstrap + Parse was really quick & awesome” – Mariya Yao.

“Thanks a lot to all and special thanks to Azat and Yuri.
I enjoyed it a lot and felt motivated to work hard to know these technologies” – Shelly Arora.

Q&A Session
Q&A Session

Next weekend, August 10–12 2012, I’m teaching the second class of “Rapid Prototyping with JavaScript and NodeJS”. I’m exited to share my experience and passion with another 10–20 smart people and make a small dent in technical education!

“Advanced Prototyping with JavaScript and NodeJS” and “Mobile Prototyping with JavaScript” trainings are coming on the weekend of August 25–26 2012. We have other cities like Los Angeles and New York in a pipeline and, (knock on wood) the future for “Rapid Prototyping” series looks very promising .