LoopBack.io with Node.js (How-to)

Let LoopBack Do It: A Walkthrough of the Node API Framework You’ve Been Dreaming Of


It’s needless to mention the growing popularity of Node.js for application development. eBay has been running a production Node API service since 2011. PayPal is actively rebuilding their front-end in Node. Walmart’s mobile site has become the biggest Node application, traffic wise. On Thanksgiving weekend in 2014, Walmart servers processed 1.5 billion requests, 70 percent of which were delivered through mobile and powered by Node.js. On the development side, the Node package manager (npm) continues to grow rapidly, recently surpassing 150,000 hosted modules.

While Ruby has Rails and Python has Django, the dominant application development framework for Node has yet to be established. But, there is a powerful contender gaining steam: LoopBack, an open source API framework built by San Mateo, Calif., company StrongLoop. StrongLoop is an important contributor to the latest Node version, not to mention the current maintainers of Express, one of the most popular Node frameworks in existence.

IMAGE: loopback and node

Let’s take a closer look at LoopBack and it’s capabilities by turning everything into practice and building an example application.

What is LoopBack and How Does It Work with Node?

LoopBack is a framework for creating APIs and connecting them with backend data sources. Built on top of Express, it can take a data model definition and easily generate a fully functional end-to-end REST API that can be called by any client.

LoopBack comes with a built-in client, API Explorer. We’ll use this since it makes it easier to see the results of our work, and so that our example can focus on building the API itself.

You will of course need Node installed on your machine to follow along. Get it here. npm comes with it, so you can install the necessary packages easily. Let’s get started.

Create a Skeleton

Our application will manage people who would like to donate gifts, or things they just don’t need anymore, to somebody who might need them. So, the users will be Donors and Receivers. A Donor can create a new gift and see the list of gifts. A Receiver can see the list of gifts from all users, and can claim any that are unclaimed. Of course, we could build Donors and Receivers as separate roles on the same entity (User), but let’s try separating them so we can see how to build relations in LoopBack. The name of this groundbreaking application will be Givesomebody.

Install the StrongLoop command line tools through npm:

$ npm install -g strongloop

Then run LoopBack’s application generator:

$ slc loopback

    |       |    .--------------------------.
    |--(o)--|    |  Let's create a LoopBack |
   `---------´   |       application!       |
    ( _´U`_ )    '--------------------------'
     |  ~  |     
 ´   `  |° ´ Y ` 

? What's the name of your application? Givesomebody

Let’s add a model. Our first model will be called Gift. LoopBack will ask for the data source and base class. Since we haven’t set up the data source yet, we can put db (memory). The base class is an auto-generated model class, and we want to use PersistedModel in this case, as it already contains all the usual CRUD methods for us. Next, LoopBack asks if it should expose the model through REST (yes), and the name of the REST service. Press enter here to use the default, which is simply the plural of the model name (in our case, gifts).

$ slc loopback:model

? Enter the model name: Gift
? Select the data-source to attach Gift to: (Use arrow keys)
❯ db (memory)
? Select model's base class: (Use arrow keys)
❯ PersistedModel
? Expose Gift via the REST API? (Y/n) Yes
? Custom plural form (used to build REST URL):

Finally, we give the names of properties, their data types, and required/not-required flags. Gift will have nameand description properties:

Let's add some Gift properties now.

Enter an empty property name when done.
? Property name: name
   invoke   loopback:property
? Property type: (Use arrow keys)
❯ string
? Required? (y/N)Yes

Enter an empty property name to indicate you are done defining properties.

The model generator will create two files which define the model in the application’s common/models: gift.json and gift.js. The JSON file specifies all metadata about the entity: properties, relations, validations, roles and method names. The JavaScript file is used to define additional behaviour, and to specify remote hooks to be called before or after certain operations (e.g., create, update, or delete).

The other two model entities will be our Donor and Receiver models. We can create them using the same process, except this time let’s put User as the base class. It will give us some properties like username, password, email out of the box. We can add just name and country, for example, to have a full entity. For the Receiver we want to add the delivery address, too.

Project Structure

Let’s have a look at the generated project structure:

IMAGE: Project Structure

The three main directories are: – /server – Contains node application scripts and configuration files. – /client – Contains .js, .html, .css, and all other static files. – /common – This folder is common to both the server and the client. Model files go here.

Here’s a detailed breakdown of the contents of each directory, taken from the LoopBack documentation:

File or directory
How to access in code

Top-level application directory

Standard npm package specification. See package.json

/server directory – Node application files 

Main application program file.

Application settings. See config.json.

Data source configuration file. See datasources.json. For an example, see Create new data source.

Model configuration file. See model-config.json. For more information, see Connecting models to data sources.

Middleware definition file. For more information, see Defining middleware.

/boot directory
Add scripts to perform initialization and setup. See boot scripts.
Scripts are automatically executed in alphabetical order.

/client directory – client application files

LoopBack generators create empty README file in markdown format.

Add your HTML, CSS, client JavaScript files.

/common directory – shared application files

Custom model files:

  • Model definition JSON files, by convention named model-name.json; for example customer.json.
  • Custom model scripts by convention named model-name.js; for example, customer.js.

For more information, see Model definition JSON file andCustomizing models.
myModel = app.models.myModelName

Build Relationships

In our example, we have a few important relationships to model. A Donor can donate many Gifts, which gives the relation Donor has many Gift. A Receiver can also receive many Gifts, so we also have the relationReceiver has many Gift. On the other side, Gift belongs to Donor, and can also belong to Receiver if the Receiver chooses to accept it. Let’s put this into the language of LoopBack.

$ slc loopback:relation

? Select the model to create the relationship from: Donor
? Relation type: has many
? Choose a model to create a relationship with: Gift
? Enter the property name for the relation: gifts
? Optionally enter a custom foreign key:
? Require a through model? No

Note that there is no through model; we are just holding the reference to the Gift.

If we repeat the above procedure for Receiver, and add two belongs to relations to Gift, we will accomplish our model design on a back end side. LoopBack automatically updates the JSON files for the models to express exactly what we just did through theses simple dialogs:

// common/models/donor.json
  "relations": {
    "gifts": {
      "type": "hasMany",
      "model": "Gift",
      "foreignKey": ""

Add a Datasource

Now let’s see how to attach a real datasource to store all of our application data. For the purposes of this example, we will use MongoDB, but LoopBack has modules to connect with Oracle, MySQL, PostgreSQL, Redis and SQL Server.

First, install the connector:

$ npm install --save loopback-connector-mongodb

Then, add a datasource to your project:

$ slc loopback:datasource

? Enter the data-source name: givesomebody
? Select the connector for givesomebody: MongoDB (supported by StrongLoop)

The next step is to configure your datasource in server/datasources.json. Use this configuration for a local MongoDB server:

  "givesomebody": {
    "name": "givesomebody",
    "connector": "mongodb",
    "host": "localhost",
    "port": 27017,
    "database": "givesomebody",
    "username": "",
    "password": ""

Finally, open server/model-config.json and change the datasource for all entities we want to persist in the database to "givesomebody".

  "User": {
    "dataSource": "givesomebody"
  "AccessToken": {
    "dataSource": "givesomebody",
    "public": false
  "ACL": {
    "dataSource": "givesomebody",
    "public": false
  "RoleMapping": {
    "dataSource": "givesomebody",
    "public": false
  "Role": {
    "dataSource": "givesomebody",
    "public": false
  "Gift": {
    "dataSource": "givesomebody",
    "public": true
  "Donor": {
    "dataSource": "givesomebody",
    "public": true
  "Receiver": {
    "dataSource": "givesomebody",
    "public": true

Testing Your REST API

It’s time to see what we’ve built so far! We’ll use the awesome built-in tool, API Explorer, which can be used as a client for the service we just created. Let’s try testing REST API calls.

In a separate window, start MongoDB with:

$ mongod

Run the application with:

$ node .

In your browser, go to http://localhost:3000/explorer/. You can see your entities with the list of operations available. Try adding one Donor with a POST /Donors call.

IMAGE: Testing Your API 2

IMAGE: Testing Your API 3

API Explorer is very intuitive; select any of the exposed methods, and the corresponding model schema will be displayed in the bottom right corner. In the data text area, it is possible to write a custom HTTP request. Once the request is filled in, click the “Try it out” button, and the server’s response will be displayed below.

IMAGE: Testing Your API 1

User Authentication

As mentioned above, one of the entities that comes pre-built with LoopBack is the User class. User possesses login and logout methods, and can be bound to an AccessToken entity which keeps the token of the specific user. In fact, a complete user authentication system is ready to go out of the box. If we try calling /Donors/login through API Explorer, here is the response we get:

  "id": "9Kvp4zc0rTrH7IMMeRGwTNc6IqNxpVfv7D17DEcHHsgcAf9Z36A3CnPpZJ1iGrMS",
  "ttl": 1209600,
  "created": "2015-05-26T01:24:41.561Z",
  "userId": ""

The id is actually the value of the AccessToken, generated and persisted in the database automatically. As you see here, it is possible to set an access token and use it for each subsequent request.

IMAGE: User Authentication

Like what you’re reading?

Get the latest updates first.

No spam. Just great engineering and design posts.

Remote Methods

A remote method is a static method of a model, exposed over a custom REST endpoint. Remote methods can be used to perform operations not provided by LoopBack’s standard model REST API.

Beside the CRUD methods that we get out of the box, we can add as many custom methods as we want. All of them should go into the [model].js file. In our case, let’s add a remote method to the Gift model to check if the gift is already reserved, and one to list all gifts that are not reserved.

First, let’s add an additional property to the model called reserved. Just add this to the properties in gift.json:

    "reserved": {
      "type": "boolean"

The remote method in gift.js should look something like this:

module.exports = function(Gift) {

    // method which lists all free gifts
    Gift.listFree = function(cb) {
            fields: {
                reserved: false
        }, cb);

    // expose the above method through the REST
    Gift.remoteMethod('listFree', {
        returns: {
            arg: 'gifts',
            type: 'array'
        http: {
            path: '/list-free',
            verb: 'get'

    // method to return if the gift is free
    Gift.isFree = function(id, cb) {
        var response;
            fields: {
                id: id
        }, function(err, gift) {
            if (err) return cb(err);

            if (gift.reserved)
                response = 'Sorry, the gift is reserved';
                response = 'Great, this gift can be yours';

        cb(null, response);

    // expose the method through REST
    Gift.remoteMethod('isFree', {
        accepts: {
            arg: 'id',
            type: 'number'
        returns: {
            arg: 'response',
            type: 'string'
        http: {
            path: '/free',
            verb: 'post'

So to find out if a particular gift is available, the client can now send a POST request to /api/Gifts/free, passing in the id of the gift in question.

Remote Hooks

Sometimes there is a need for execution of some method before or after the remote method. You can define two kinds of remote hooks:

  • beforeRemote() runs before the remote method.
  • afterRemote() runs after the remote method.

In both cases, you provide two arguments: a string that matches the remote method to which you want to “hook” your function, and the callback function. Much of the power of remote hooks is that the string can include wildcards, so it is triggered by any matching method.

In our case, let’s set a hook to print information to the console whenever a new Donor is created. To accomplish this, let’s add a “before create” hook in donor.js:

module.exports = function(Donor) {
    Donor.beforeRemote('create', function(context, donor, next) {
        console.log('Saving new donor with name: ', context.req.body.name);

The request is called with the given context, and the next() callback in middleware (discussed below) is called after the hook runs.

Access Controls

LoopBack applications access data through models, so controlling access to data means defining restrictions on models; that is, specifying who or what can read and write the data or execute methods on the models. LoopBack access controls are determined by access control lists, or ACLs.

Let’s allow unlogged-in Donors and Receivers to view gifts, but only logged-in Donors to create and delete them.

$ slc loopback:acl

To begin, let’s deny everyone access to all endpoints.

? Select the model to apply the ACL entry to: Gift
? Select the ACL scope: All methods and properties
? Select the access type: All (match all types)
? Select the role: All users
? Select the permission to apply: Explicitly deny access

Next, allow everyone to read from Gift models:

$ slc loopback:acl

? Select the model to apply the ACL entry to: Gift
? Select the ACL scope: All methods and properties
? Select the access type: Read
? Select the role: All users
? Select the permission to apply: Explicitly grant access

Then, we want to allow authenticated users to create Gifts:

$ slc loopback:acl

? Select the model to apply the ACL entry to: Gift
? Select the ACL scope: A single method
? Enter the method name: create
? Select the role: Any authenticated user
? Select the permission to apply: Explicitly grant access

And finally, let’s allow the owner of the gift to make any changes:

$ slc loopback:acl

? Select the model to apply the ACL entry to: Gift
? Select the ACL scope: All methods and properties
? Select the access type: Write
? Select the role: The user owning the object
? Select the permission to apply: Explicitly grant access

Now when we review gift.json, everything should be in place:

"acls": [
    "accessType": "*",
    "principalType": "ROLE",
    "principalId": "$everyone",
    "permission": "DENY"
    "accessType": "READ",
    "principalType": "ROLE",
    "principalId": "$everyone",
    "permission": "ALLOW"
    "accessType": "EXECUTE",
    "principalType": "ROLE",
    "principalId": "$authenticated",
    "permission": "ALLOW",
    "property": "create"

One important note here: $authenticated is a predefined role which corresponds to all users in the system (both Donors and Receivers), but we only want to allow Donors to create new Gifts. Therefore, we need a custom role. As Role is one more entity we get out of the box, we can leverage its API call to create the $authenticatedDonor role in the boot function, and then just modify pricipalId in gift.json.

It will be necessary to create a new file, server/boot/script.js, and add the following code:

    name: 'authenticatedDonor'
}, function(err, role) {
    if (err) return debug(err);

The RoleMapping entity maps Roles to Users. Be sure that Role and RoleMapping are both exposed through REST. In server/model-config.json, check that "public" is set to true for the Role entity. Then in donor.js, we can write a “before create” hook that will map the userID and roleID in the RoleMapping POST API call.


Middleware contains functions that are executed when a request is made to the REST endpoint. As LoopBack is based on Express, it uses Express middleware with one additional concept, called “middleware phases.” Phases are used to clearly define the order in which functions in middleware are called.

Here is the list of predefined phases, as provided in the LoopBack docs:

  1. initial – The first point at which middleware can run.
  2. session – Prepare the session object.
  3. auth – Handle authentication and authorization.
  4. parse – Parse the request body.
  5. routes – HTTP routes implementing your application logic. Middleware registered via the Express API app.use, app.route, app.get (and other HTTP verbs) runs at the beginning of this phase. Use this phase also for sub-apps like loopback/server/middleware/rest or loopback-explorer.
  6. files – Serve static assets (requests are hitting the file system here).
  7. final – Deal with errors and requests for unknown URLs.

Each phase has three subphases. For example, the subphases of the initial phase are:

  1. initial:before
  2. initial
  3. initial:after

Let’s take a quick look on our default middleware.json:

  "initial:before": {
    "loopback#favicon": {}
  "initial": {
    "compression": {},
    "cors": {
      "params": {
        "origin": true,
        "credentials": true,
        "maxAge": 86400
  "session": {
  "auth": {
  "parse": {
  "routes": {
  "files": {
  "final": {
    "loopback#urlNotFound": {}
  "final:after": {
    "errorhandler": {}

In the initial phase, we call loopback.favicon() (loopback#favicon is the middleware id for that call). Then, third-party npm modules compression and cors are called (with or without parameters). In the final phase, we have two more calls. urlNotFound is a LoopBack call, and errorhandler is third-party module. This example should demonstrate that a lot of built in calls can be used just like the external npm modules. And of course, we can always create our own middleware and call them through this JSON file.


To wrap up, let’s mention a module which exports the boot() function that initializes the application. In server/server.js you’ll find the following piece of code, which bootstraps the application:

boot(app, __dirname, function(err) {
    if (err) throw err;
    // start the server if `$ node server.js`
    if (require.main === module)

This script will search the server/boot folder, and load all the scripts it finds there in alphabetical order. Thus, in server/boot, we can specify any script which should be run at start. One example is explorer.js, which runs API Explorer, the client we used for testing our API.

Got the repetition blues? Don’t build that Node API from scratch again. Let LoopBack do it!


Before I leave you, I would like to mention StrongLoop Arc, a graphical UI that can be used as an alternative to slc command line tools. It also includes tools for building, profiling and monitoring Node applications. For those who are not fans of the command line, this is definitely worth trying.

IMAGE: Conclusion

Generally speaking, LoopBack can save you a lot of manual work since you are getting a lot of stuff out of the box. It allows you to focus on application-specific problems and business logic. If your application is based on CRUD operations and manipulating predefined entities, if you are sick of rewriting the user’s authentication and authorization infrastructure when tons of developers have written that before you, or if you want to leverage all the advantages of a great web framework like Express, then building your REST API with LoopBack can make your dreams come true. It’s a piece of cake!


Happy Coding Smile

Angular 2.0 Architechture

Starting new series – Learning Angular 2.0 on My Github –


##### angular 2.0 building blocks
– Module
– Component
– Template
– Metadata
– Data Binding
– Service
– Directive
– Dependency Injection

##### 1. Module
– Angular apps are modular and so in general we assemble our application from many modules. A typical module is a cohesive block of code dedicated to a single purpose.
– A module exports something of value in that code, typically one thing such as a class.
– Some modules are libraries of other modules.
– Angular itself ships as a collection of library modules called “barrels”. Each Angular library is actually a public facade over several logically related private modules.
– The angular2/core library is the primary Angular library module from which we get most of what we need.
– There are other important Angular library modules too such as angular2/common, angular2/router, and angular2/http.
– e.g import {Component} from ‘angular2/core’;
– The key take aways are:
    – Angular apps are composed of modules.
    – Modules export things — classes, function, values — that other modules import.
    – We prefer to write our application as a collection of modules, each module exporting one thing.
    – The first module we write will most likely export a component.

##### 2. Component
– Perhaps the first module we meet is a module that exports a component class. The component is one of the basic Angular blocks, we write a lot of them
– Most applications have an AppComponent. By convention, we’ll find it in a file named app.component.ts
– Components are the collection of templates, styles, selector configurations etc.
– Angular creates, updates, and destroys components as the user moves through the application.
– Each components is a typescript class which again includes variable, functions, prop declaration etc.

##### 3. Template
– We define a Component’s view with its companion template. A template is a form of HTML that tells Angular how to render the Component.
– A template looks like regular HTML much of the time … and then it gets a bit strange.
– Template will have all diff type databinding and html DOM information.

##### 4. Metadata
– Metadata tells Angular how to process a class.
– e.g
  selector:    ‘hero-list’,
  templateUrl: ‘app/hero-list.component.html’,
  directives:  [HeroDetailComponent],
  providers:   [HeroService]
Here we see the @Component decorator which (no surprise) identifies the class immediately below it as a Component class.

selector – a css selector that tells Angular to create and insert an instance of this component where it finds a <hero-list> tag in parent HTML. If the template of the application shell (a Component) contained

templateUrl – the address of this component’s template

directives – an array of the Components or Directives that this template requires.

providers – an array of dependency injection providers for services that the component requires. This is one way to tell Angular that our component’s constructor requires a HeroService so it can get the list of heroes to display.

##### 5. Data Binding
– There are four forms of data binding syntax.
– Each form has a direction – to the DOM, from the DOM, or in both directions.
– We can group all bindings into three categories by the direction in which data flows. Each category has its distinctive syntax:
    – One Way (from component -> View)   – Binds Property, Attributes, Class, Style.
    [target] = “expression”
    bind-target = “expression”
    – One Way (from View -> Component) – Binds Events
    (target) = “Statement”
    – Two way binding
    [(target)] = “expression”
    bindon-target =”expression”
For More Details – https://angular.io/docs/ts/latest/guide/template-syntax.html

##### 6. Directive
– Our Angular templates are dynamic. When Angular renders them, it transforms the DOM according to the instructions given by a directive.
– A directive is a class with directive metadata. In TypeScript we’d apply the @Directive decorator to attach metadata to the class.
– While the component is technically a directive, it is so distinctive and central to Angular applications that we chose to separate the component from the directive in our architectural overview.
– There are two other kinds of directives as well that we call “structural” and “attribute” directives.
– Structural directives alter layout by adding, removing, and replacing elements in DOM.
    – e.g *ngFor , *ngIf etc.
– Attribute directives alter the appearance or behavior of an existing element. In templates they look like regular HTML attributes, hence the name.
    – e.g. [(ngModel)]

##### 7. Service
– “Service” is a broad category encompassing any value, function or feature that our application needs.
– Almost anything can be a service. A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.
    – Examples include:
        – logging service
        – data service
        – message bus
        – tax calculator
        – application configuration
– Most common usage of services are to bind components with Databases or any similar part which delivers data to components and that way, components will be independent from Data Layer.

##### 8. DI (Dependency Injection)
– “Dependency Injection” is a way to supply a new instance of a class with the fully-formed dependencies it requires. Most dependencies are services. Angular uses dependency injection to provide new components with the services they need.
– dependency injection is wired into the framework and used everywhere.
– the Injector is the main mechanism.
    – an injector maintains a container of service instances that it created.
    – an injector can create a new service instance using a provider.
– a provider is a recipe for creating a service.
– we register providers with injectors.

##### 9. Other Stuff
– Animation: A forthcoming animation library makes it easy for developers to animate component behavior without deep knowledge of animation techniques or css.
– Bootstrapping: A method to configure and launch the root application component.
– Change Detection: Learn how Angular decides that a component property value has changed and when to update the screen
– Zones: Change Detection uses zones to intercept asynchronous activity and run its change detection strategies.
– Events: The DOM raises events. So can components and services.
– Router: With the Component Router service, users can navigate a multi-screen application in a familiar web browsing style using URLs.
– Forms: Support complex data entry scenarios with HTML-based validation and dirty checking.
– Http: Communicate with a server to get data, save data, and invoke server-side actions with this Angular HTTP client.
– Lifecycle Hooks: We can tap into key moments in the lifetime of a component, from its creation to its destruction, by implementing the “Lifecycle Hook” interfaces.
– Pipes: Services that transform values for display. We can put pipes in our templates to improve the user experience.
    price | currency:’USD’:true
– Testing: Angular provides a testing library for “unit testing” our application parts as they interact with the Angular framework.

### Author
Bhavin Patel

Happy Coding Smile

Angular 2.0–Beginners Guide


A curated list of helpful material to start learning Angular 2

Basic Introduction Video Series by Mindspace and Code Samples by me (Bhavin Patel)
(Video Series link is in my github)



Angular 2 Explained

Angular 2 Forms

Angular 2 Docs

Angular 2 Integrations




Example Apps

Live Code Experiments

Angular 2 Material

Stack Overflow Questions





Social Media

Angular 2 Dart

TypeScript Definitions

Thanks to  timjacobi/angular2-education for this great compilation.

Happy Coding Smile

angular- Dynamic window height with ng-style

Recently, I was working on one nw.js (Node-webkit) related project for creating windows / desktop application using node/nw.js. I had to write window resize event and based on that I needed to show vertical scrollbar.

in short something like – where height and scrollbar will adapt window resize automatically upon resize.


angular code

app.directive(‘winResize’, function ($window) {
    return function (scope, element, attr) {

        var w = angular.element($window);
        scope.$watch(function () {
            return {
                ‘h’: window.innerHeight,
                ‘w’: window.innerWidth
        }, function (newValue, oldValue) {
            console.log(newValue, oldValue);
            scope.windowHeight = newValue.h;
            scope.windowWidth = newValue.w;

            scope.resizeWithOffset = function (offsetH) {
                return {
                    ‘height’: (newValue.h – offsetH) + ‘px’                   

        }, true);

        w.bind(‘resize’, function () {

HTML code


window.height: {{windowHeight}}

window.width: {{windowWidth}}

Hope this helps someone in need…!! Happy Coding Smile

ionic, angularjs with VS2013

This walk through will show you how to combine the features of Visual Studio 2013 with the Apache Cordova CTP 3.1, AngularJS, Ionic, and Adobe PhoneGap to create, build, and deploy a hybrid mobile app.

While Microsoft is hard at work putting the final touches on Visual Studio 2015 support for web based mobile apps, you can get started today if you know how to put the right pieces together.  This primer is intended to get you up and running building a hybrid mobile app using tools available today including Visual Studio 2013, Apache Cordova, AngularJS, the Ionic Framework, and Adobe Phone Build.

Visit – http://www.wintellect.com/devcenter/paulballard/build-your-first-hybrid-mobile-app-with-visual-studio-2013-angularjs-ionic-and-adobe-phonegap#

Happy Coding 🙂

How-to with Node.jS & file system

1. Reading from a file

You want to read a file from the file system and display its contents on the terminal screen.

var fs = require('fs');
fs.readFile('data.txt', function (err, data) {  if (err)    throw err;  if (data)    console.log(data.toString('utf8'));

First, we include the file system core module using module inclusion as written: var fs = require(‘fs’);  allowing us to utilize all the features of the fs module using our variable we defined as fs. The next line states our input file ‘data.txt’. The next part of this line will attach our anonymous callback function function (err, data) to the actual file read operation readFile.

Our anonymous callback function accepts any errors which occur as  err, and the resulting file data as a binary buffer array  data. Within the anonymous function, we first check for any potential errors and throw the error as an exception to be left to be caught by the calling process as if (err)  throw err; . The subsequent lines check to see if the data is not null, and then converts the data to a UTF-8 encoded string to be written to the console screen if (data) console.log(data.toString(‘utf8′));

It is important to note that this solution uses the asynchronous file read operation to prevent blocking. For a synchronous, or blocking file read operation, reference the Node.js documentation for readFileSync()

var fs = require('fs');
fs.writeFile('data2.txt', 'Hello, World!', function (err) {
     if (err)
       throw err;

First, we include the file system core module using module inclusion as written: var fs = require(‘fs’);  allowing us to utilize all the features of the fs module using our variable we defined as fs.  The next line states our input file ‘data2.txt’ along with a string of the text we want to write to the file ‘Hello, World!’. The next part of this line will attach our anonymous callback function function (err) to the actual file write operation writeFile(). Our anonymous callback function accepts any errors which occur as  err. Within the anonymous function, we also check for any potential errors and throw the error as an exception to be left to be caught by the calling process as if (err)  throw err; .
It is important to note that this solution uses the asynchronous file write operation to prevent blocking. For a synchronous, or blocking file write operation, reference the Node.js documentation for writeFileSync()

3. Working with directories

You want to read through a list of all of the files in a given directory location and display each file’s name.

var fs = require('fs');
fs.readdir('.', function (err, files) {
 if (err)
    throw err;
 for (var index in files) {

First, we include the file system core module using module inclusion as written: var fs = require(‘fs’);  allowing us to utilize all the features of the fs module using our variable we defined as fs.  The next line states our input directory ‘.’ (the current working directory). The next part of this line will attach our anonymous callback function function (err, files) to the actual directory read operation readdir(). Our anonymous callback function accepts any errors which occur as  err and an array of filenames stored in files.

Within the anonymous function, we first check for any potential errors and throw the error as an exception to be left to be caught by the calling process as if (err)  throw err;. Next we iterate over each item in the filename array and display each filename on the console screen.

It is important to note that this solution uses the asynchronous directory read operation to prevent blocking. For a synchronous, or blocking directory reading operation, reference the Node.js documentation for readdirSync()

4. Traversing the file system

You want to recursively read through a list of all of the files in a given directory location and display each file’s name or recursively traverse the file if it is a directory.

 var fs = require('fs');
 var traverseFileSystem = function (currentPath) {
    var files = fs.readdirSync(currentPath);
    for (var i in files) {
       var currentFile = currentPath + '/' + files[i];
       var stats = fs.statSync(currentFile);
       if (stats.isFile()) {
      else if (stats.isDirectory()) {

First, we include the file system core module using module inclusion as written: var fs = require(‘fs’);  allowing us to utilize all the features of the fs module using our variable we defined as fs.  The next line defines our custom function traverseFileSystem which accepts one parameter currentPath which contains the current directory path the function is traversing.

The first line of this function simply displays the current directory’s name. Next we synchronously return a list of files contained in the current directory (this is done synchronously to guarantee we have a list of files before we try to traverse them). Next we iterate over each item in the filename array. From here we create a variable to store our fully-qualified file path and obtain information about that file using a synchronous file stats call  statSync() (this function is described in more depth in the next example).

The function then checks if the current file is a file or a directory, and either displays the file’s name if it is a file or recurses by re-invoking the traverseFileSystem function using the new current directory path if it is a directory. The last line of the code invokes the  traverseFileSystem function on ‘..’ which is a simple way to reference the parent directory of the current working directory.

It is important to note that this solution uses the synchronous versions of some of the asynchronous methods used in previous examples in order to guarantee return values before proceeding with the code’s execution. This was done in the sake of simplicity in illustration of this solution and can be ported into an asynchronous version with little difficulty

5. Getting/setting file attributes

You want to get certain attributes of a given file such as whether or not it is a file or a directory, and you want to be able to set certain attributes such as the file’s name or the file’s permissions.

 var fs = require('fs');
 fs.stat('data.txt', function (err, stats) {
  if (err)
     throw err;
  if (stats.isFile()) {
      console.log('It\'s a file!');
  if (stats.isDirectory()) {
    console.log('It\'s a directory!');
  for (var i in stats) {
     if ('function' !== typeof stats[i])
     console.log(i + '\t= ' + stats[i]);
 fs.rename('data2.txt', 'data2_new.txt', function (err) {
  if (err)
    throw err;
 fs.chmod('data3.txt', '0777', function (err) {
   if (err)
      throw err;
   console.log('File permissions changed!');

First, we include the file system core module using module inclusion as written: var fs = require(‘fs’);  allowing us to utilize all the features of the fs module using our variable we defined as fs.

The next line obtains information about a given file ‘data.txt’ using an asynchronous file stats call  stat(). On this same line we specify our anonymous callback function function (err, stats) which takes two parameters: any errors which occur as  err and a stats object of the given file as stats. Within the anonymous function, we first check for any potential errors and throw the error as an exception to be left to be caught by the calling process as if (err)  throw err;.

We then display on the console screen whether the given file is a file or a directory. After this, we step through each non-function member of the stats object and display what that member field’s name is and what value it contains (this will include detailed file information such as creation date, modified date, file size, etc).

The next section of the code executes the asynchronous rename() function to rename the file ‘data2.txt’ to ‘data2_new.txt’. In this same line, we are passing the anonymous callback function function (err) which, as before, passes any potential errors that might occur as its only parameter err.

We then use the same technique to check for any errors and then display ‘Renamed!’ if the file was successfully renamed. In the last section of the code we execute the asynchronous chmod() function to change the file permissions of our input file ‘data3.txt’ to ’0777′ (or all read-write-execute). In this same line, we are passing the anonymous callback function function (err) which, as before, passes any potential errors that might occur as its only parameter err. We then use the same technique to check for any errors and then display ‘File permissions changed!’ if the file permissions were successfully changed.

6. Watching a file for changes

You want to be notified of any changes that occur within a given directory either to the directory’s contents or directory itself.


This solution requires a special module called “inotify.” Assuming you have the node package manager installed, you can install inotify using: npm install inotify The code below must then reference the install path:

 var fs = require('fs');
 var Inotify = require('/usr/local/node/node_modules/inotify').Inotify;
 var inotify = new Inotify();
 var watcher = {
 path: '.',
 watch_for: Inotify.IN_OPEN | Inotify.IN_CLOSE,
 callback: function (event) {
 var file = event.name ? event.name : '';
 var mask = event.mask;
 if (file != '' && file.indexOf('.') !== 0) {
    if (mask & Inotify.IN_OPEN) {
    console.log(file + ' was opened ');
 else if (mask & Inotify.IN_CLOSE) {
    console.log(file + ' was closed ');

First, we include the file system core module using module inclusion as written: var fs = require(‘fs’);  allowing us to utilize all the features of the fs module using our variable we defined as fs. We then include the inotify modulevar inotify = require(‘/usr/local/node/node_modules/inotify’).Inotify;  (note that this path should be whatever path you installed the inotify module to). On the next line, we are instantiating the inotify object new Inotify(); which we will use for watching for file changes.

The next few lines are all for defining our  watcher object with the following properties: path: ‘.’ (the path to the file we want to watch—in this case, we are watching the current working directory), watch_for: Inotify.IN_OPEN | Inotify.IN_CLOSE (specifying that we will only be firing change events when a file is opened or closed), and lastly, callback: function (event) {  … } (defines our callback function that will be fired whenever the above two events are emitted). In the first line of our callback, we are getting the filename from the event object var file = event.name ? event.name : ”;  (if the filename is null, we’ll set the variable to an empty string).

The next line is just to make a “shorthand” variable for the event type mask var mask = event.mask; .  The next conditional statement will filter out empty filenames and filenames that start with a “.” (which sometimes indicate a temporary file being used to write a file). The next couple of statements if (mask & Inotify.IN_OPEN) {  … } and then after  else if (mask & Inotify.IN_CLOSE) {  … }  will display whether there was a file opened or closed under the given directory location.

Lastly is a very important line of code where we add our watcher object that we just defined to the inotify object using inotify.addWatch(watcher); (note that without this very line, our watcher object is essentially useless).

For more info – https://nodejs.org/api/fs.html

Happy Coding Smile

Everything about Node.js (How-to-start)


Developer Sites







JavaScript resources

Node.js Modules


Happy Coding Smile

11 Tips to Improve AngularJS Performance


1. Minimize/Avoid Watchers

Usually, if your Angular app is slow, it means that you either have too many watcher, or those watchers are working harder then they should.

Angular uses dirty checking to keep track of all the changes in app. This means it will have to go through every watcher to check if they need to be updated (call the digest cycle). If one of the watcher is relied upon by another watcher, Angular would have to re-run the digest cycle again, to make sure that all of the changes has propagated. It will continue to do so, until all of the watchers have been updated and app has stabilized.

Even though running JavaScript in modern browsers is really fast, in Angular it is fairly easy to add so many watchers that you app will slow down to a crawl.

Keep in mind the following when implementing or refactoring an Angular app.

  1. Watches are set on:
    • $scope.$watch
    • {{ }} type bindings
    • Most directives (i.e. ng-show)
    • Scope variables scope: { bar: '='}
    • Filters {{ value | myFilter }}
    • ng-repeat
  2. Watchers (digest cycle) run on
    • User action (ng-click etc). Most built in directives will call $scope.apply upon completion which triggers the digest cycle.
    • ng-change
    • ng-model
    • $http events (so all ajax calls)
    • $q promises resolved
    • $timeout
    • $interval
    • Manual call to $scope.apply and $scope.digest

2. Avoid ng-repeat. If you have to use ng-repeat use infinite scrolling or pagination

This was the biggest win for our app. I am not going to go into too much details, but I found the article bellow to be extremely helpful.


In addition to infinite scroll, make sure to use track by when possible.https://docs.angularjs.org/api/ng/directive/ngRepeat#tracking-and-duplicates

For example a unique step id, is a good value to track by when doing an ng-repeat.

<li ng-repeat="Task in Tasks track by Task.Id></li>

3. Use Bind once when possible

Angular 1.3 added :: notation to allow one time binding. In summary, Angular will wait for a value to stabilize after it’s first series of digest cycles, and will use that value to render the DOM element. After that, Angular will remove the watcher forgetting about that binding.

If you are on pre 1.3 version of Angular you can use this library to achieve similar results:

4. Use $watchCollection instead of $watch (with a 3rd parameter)

$watch with only 2 parameters, is fast. However, Angular supports a 3rd parameter to this function, that can look like this: $watch('value', function(){}, true). The third parameter, tells Angular to perform deep checking, meaning to check every property of the object, which could be very expensive.

To address this performance issue, angular added $watchCollection('value', function(){}). $watchColleciton acts almost like $watch with a 3rd parameter, except it only checks the first layer of object’s properties, thus greatly improving the performance.

Official doc:

Helpful blog post:

5. Avoid repeated filters and cache data whenever possible

One time binding does not seem to play well with filters. There seems to be work arounds to make it work, but I think it’s cleaner and more intuitive to simply assign the needed value to a variable (or set it as a property on an object, if you are dealing with a lot of variables).

For example, instead of:

{{'DESCRIPTION' | translate }}

You can do:
– In JavaScript $scope.description: $translate.instant('DESCRIPTION')
– In HTML {{::description}}

Or instead of: {{step.time_modified | timeFormatFilter}}

  • In JavaScript

var timeFormatFilter = $filter(‘timeFormatFilter’);

step.time_modified = timeFormatFilter(step.time_modified);

  • In HTML {{::Path.time_modified}}

6. Debounce ng-model

If you know there is going to be a lot of changes coming from an ng-model, you can de-bounce the input.

For example if you have a search input like Google, you can de-bounce it by setting the following ng-model option: ng-model-options="{ debounce: 250 }.

This will ensure that the digest cycle due to the changes in this input model will get triggered no more then once per 250ms .


7. Use ng-if instead of ng-show (but confirm that ng-if is actually better for your use case)

ng-show will render an element, and use display:none to hide it,
ng-if will actually removes the element from DOM, and will re-create it, if it’s needed.

You may need ng-show for an elements that toggles on an off often, but for 95% of the time, ng-if is a better way to go.

8. Use console.time to benchmark your functions

console.time is a great API, and I found it particularly helpful when debugging issues with Angular performance. I placed a number of those calls through out my code, to help me confirm that my re-factoring was in fact improving the performance.


The API looks as such:


//Some code


And here is a simple example:




}, 100);

//In console $: TimerName: 100.324ms

Note: If console.time is not precise enough for your needs, you can get a more accurate reading using performance.now(). You will have to do your own math, if you choose to take this path.


totalTime = 0; count = 0;

var someFunction = function() {

var thisRunStartTime = performance.now();


// some code

// some more code

totalTime += performance.now() – thisRunStartTime;


console.log(“Average time: ” + totalTime/count);

9. Use native JavaScript or Lodash for slow functions

Our app was already using lodash, so there was no overhead for me to use it in my optimization. If lodash was not include, I would probably try to re-write everything in native JavaScript.

In my tests I got a significant performance boost by simply re-writing some of the basic logic with lodash, instead of relying on built-in Angular methods (which have to account for much more generic use cases).

Maintainer of Lodash John-David Dalton is also a co-creator of https://jsperf.com/, and he is all about the performance. So I trust him and his library when it comes to speed.

10. Use Batarang to benchmark your watchers

Batarang is a great tool from the Angular team, and it was very helpful in my debugging efforts. It has a lot of useful features, but the one that was the most relevant to this use-case is the performance tab.


Make sure to get the stable version, which seems to work for the majority of users.

Watch this video to get more insight into the Batarang.

11. Use Chrome Timeline and Profiler to identify performance bottlenecks

I like to think of myself as a Chrome Dev Tools power user. But it’s not often that I get a to use the Timeline and Profiler views. In this project, both were extremely helpful.

Pro Tip: If you use console.time API (see tip #8), the time period will get highlighted on your timeline snapshot. So you can examine the exact time period that you care about the most.


The timeline view, and the magic 60fps line is crucial. When I started on our project, the app was rendering full steam for 15 seconds or more, becoming almost completely unresponsive to the user.


After performance optimization, the app now fully renders in less then 2 seconds (note that the time scale is different), allowing users to freely interact with the user interface after a relatively short delay.


It is clear from looking at the image that the app could be further optimized. But even as is, I am very happy with the improvements to the user experience.

To get more experience with Timeline view, check out these web audits by Paul Irish:


Finally, I wanted to mentioned the Profiling tab in Chrome Dev tools, and the JavaScript CPU profiler in particular. It has 3 views:

1. Chart view is similar to the timeline, but it makes it a bit easier to jump to the source code of the function of interest.


2. Heavy (Bottom up view)
This view identifies heavy user functions, and shows you the reverse call stack to help pinpoint origination of the function. Note how $digest comes before the $apply, indicating the reverse order.


3. Tree (Top Down)
Exposes the functions from which the heavy consumption originated, and then you can drill down to find the offending function.

Also note the yellow triangle with a “!”, if you however over it, it will identify a potential optimization problem.



Thanks to Alex Kras for Sharing wonderful article across developers.

Happy Coding Smile

ionic-content overlaps/hide behind ion-header-bar/ion-nav-bar.

Recently I am working on Ionic Framework with AngularJS. I noticed that my <ion-content> was overlapping or hidden behind <ion-nav-bar> or in some cases you may have <ion-header-bar> as well..

       <ion-header-bar class="bar bar-header bar-dark">
      <h1 class="title">Settings</h1>
      <button class="button button-clear" ng-click="closeSettings()">Close</button>
      <div class="padding">
        <div class="list">
          <label class="item item-input">
            <span class="input-label">Units</span>

            <ion-radio-buttons ng-model="settings.tempUnits">
              <button class="button button-positive button-radio" ng-value="'f'">&deg;F</button>
              <button class="button button-positive button-radio" ng-value="'c'">&deg;C</button>


Assign a class=”has-header” to ion-content.

<ion-content class="has-header">

Hope this helps –

Happy Android/ionic/angular Coding 🙂