NodeJs : Convert json to csv using node module

Its very common usecase to convert json docs or Mongo doucments into csv and share with other. I am sharing a simple node module with example to accomplish the same.

Details of package - https://www.npmjs.com/package/json2csv

# To install node module from cmd 
npm install json2csv --save



# create a converter.js javascript file as below with you input json and mapping.

var json2csv = require('json2csv');
var fs = require('fs');
var fields = ['car.make', 'car.model', 'price', 'color'];
var myCars = [

    {
        "car": {
            "make": "Hundai", "model": "sonata"
        },
        "price": 30000,
        "color": "white"
    },
    {
        "car": {
            "make": "Audi", "model": "A3"
        },
        "price": 40000,
        "color": "blue"
    }, {
        "car": {"make": "BMW", "model": "F20"},
        "price": 35000,
        "color": "black"
    }, {
        "car": {"make": "Porsche", "model": "9PA AF1"},
        "price": 60000,
        "color": "green"
    }
];
var csv = json2csv({ data: myCars, fields: fields });

fs.writeFile('file.csv', csv, function(err) {
if (err) throw err;
console.log('file saved');
});


# now run javascript file on node
node converter.js

# This will create a csv file in the current directory called as file.csv open it in excell and you are done.

JavaScript : Closure Program

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();

function myFunction(){
document.getElementById(“demo”).innerHTML = add();
}

Example Explained

The variable add is assigned the return value of a self-invoking function.

The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.

This way add becomes a function. The “wonderful” part is that it can access the counter in the parent scope.

This is called a JavaScript closure. It makes it possible for a function to have “private” variables.

The counter is protected by the scope of the anonymous function, and can only be changed using the add function.

A closure is a function having access to the parent scope, even after the parent function has closed.

Javascript : Non blocking / Async example

/**
 * Created by Aseem on 12/7/16.
 */

console.log("1: Start app")

var slowProcess = setTimeout(function(){
    console.log("2: app processing async - non blocking ");
},1000);

console.log("3: Exit app")

 

The out of this is non blocking, which mean the flow will not wait  or get blocked for slowProcess

Sample console output

➜ async git:(master) ✗ node nonBlocking.js
1: Start app
3: Exit app
2 : app processing async – non blocking

 

What is ISO date format

As world is becoming a big family with globalization, we need the standard to followed to avoid confusion especially related to date and time. If every country or person would write dates in different format, it would be confusing to figure out exact date while doing communication across countries, hence ISO has come up with ISO date format to be followed by every one. 

International Standard ISO 8601 specifies numeric representations of date and time. This standard notation helps to avoid confusion in international communication caused by the many different national notations and increases the portability of computer user interfaces.

YYYY-MM-DDThh:mm:ss.sTZD

where:

     YYYY = four-digit year

     MM   = two-digit month (01=January, etc.)

     DD   = two-digit day of month (01 through 31)

     hh   = two digits of hour (00 through 23) (am/pm NOT allowed)

     mm   = two digits of minute (00 through 59)

     ss   = two digits of second (00 through 59)

     s    = one or more digits representing a decimal fraction of a second

     TZD  = time zone designator (Z or +hh:mm or -hh:mm)

example: 

 1997-07-16T19:20:30.45Z (Z at end indicates time is taken with Zero correction i.e. UTC time)

 1997-07-16T19:20:30.45+01:00 (+1:00 at end indicates time is taken at time zone which is 1:00 ahead of UTC time)

Advantages of the ISO 8601 standard date notation compared to other commonly used variants:

  • easily readable and writeable by software (no ‘JAN’, ‘FEB’, … table necessary)
  • easily comparable and sortable with a trivial string comparison
  • language independent
  • can not be confused with other popular date notations
  • consistency with the common 24h time notation system, where the larger units (hours) are also written in front of the smaller ones (minutes and seconds)
  • strings containing a date followed by a time are also easily comparable and sortable (e.g. write “1995-02-04 22:45:00”)
  • the notation is short and has constant length, which makes both keyboard data entry and table layout easier
  • identical to the Chinese date notation, so the largest cultural group (>25%) on this planet is already familiar with it 🙂
  • date notations with the order “year, month, day” are in addition already widely used e.g. in Japan, Korea, Hungary, Sweden, Finland, Denmark, and a few other countries and people in the U.S. are already used to at least the “month, day” order
  • a 4-digit year representation avoids overflow problems after 2099-12-31

why not allow the name in the name/value pairs to be unquoted identifiers

Quote names with " is a lot simpler than “You may quote names with " or ' but you don’t have to, unless they contain certain characters (or combinations of characters that would make it a keyword) and ' or " may need to be quoted depending on what delimiter you selected.

Unquoted key name problem :

It turns out ECMA Script 3 has a whack reserved word policy. Reserved words must be quoted in the key position, which is really a nuisance. When I got around to formulizing this into a standard, I didn’t want to have to put all of the reserved words in the standard, because it would look really stupid.(

NOTE : These days you can even use reserve words without quotes, you only need quotes when you have some quotes or special character.

Splice to add, replace and remove javascript array

Here is working code link : http://plnkr.co/edit/SHfpFQ?p=preview

Splice is an effective way to add, replace or remove elements from specific index in Javascript Array.

Javascript array splice() method changes the content of an array, adding new elements while removing old elements.

Syntax

Its syntax is as follows −

array.splice(index, howMany, [element1][, ..., elementN]);

Parameter Details

  • index − Index at which to start changing the array.
  • howMany − An integer indicating the number of old array elements to remove. IfhowMany is 0, no elements are removed.
  • element1, …, elementN − The elements to add to the array. If you don’t specify any elements, splice simply removes the elements from the array.

Return Value

Returns the extracted array based on the passed parameters.

If you specify a different number of elements to insert than the number you’re removing, the array will have a different length at the end of the call.

Examples

Using splice()

The following script illustrates the use of splice():

var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];

// removes 0 elements from index 2, and inserts 'drum'
var removed = myFish.splice(2, 0, 'drum');
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removed is [], no elements removed

// removes 1 element from index 3
removed = myFish.splice(3, 1);
// myFish is ['angel', 'clown', 'drum', 'surgeon']
// removed is ['mandarin']

// removes 1 element from index 2, and inserts 'trumpet'
removed = myFish.splice(2, 1, 'trumpet');
// myFish is ['angel', 'clown', 'trumpet', 'surgeon']
// removed is ['drum']

// removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue'
removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon']
// removed is ['angel', 'clown']

// removes 2 elements from index 3
removed = myFish.splice(3, Number.MAX_VALUE);
// myFish is ['parrot', 'anemone', 'blue']
// removed is ['trumpet', 'surgeon']

javaScript inheritance

image

Summary

  • You cause a class to inherit using ChildClassName.prototype = new ParentClass();.
  • You need to remember to reset the constructor property for the class using ChildClassName.prototype.constructor=ChildClassName.
  • You can call ancestor class methods which your child class has overridden using the Function.call() method.
  • Javascript does not support protected methods.