Tuesday, June 30, 2020

python pandas series

Pandas Series


pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False) 

Pandas Series represents a one-dimensional ndarray with axis labels. It is not necessary for the labels to be unique but they should be hashtable type. Series supports both integer-based indexing and non-integer based indexing. A Series has two columns, first for the index and the second for the actual data. Series has the following parameters, 

pandas series



Data 

The data can be array-like, Iterable, dict, or scalar value 

Index

It can be array-like or Index (1-dimension). The values must be hashtable. It must be of the same length as data. If index is not passed, by default np.arrange(n) is applied.

dtype

It can be str, NumPy.dtype, or ExtensionDtype. This field defines the data type for the output Series. If it is not defined, this will be inferred from the data. This field is optional.

Copy

This field is used for copying the data.

Creating a Series from pandas


Create an empty series


import pandas as pd  
# import Pandas 
  
# Generate the empty series 

a = pd.Series() 
print(a)

#output
Series([], dtype: float64)

Create a series with a list


import pandas as pd  
# import Panda 
  
# Generate the series with Data, and Index 
index =[1, 3, 4, 5, 6, 2, 9] 
Data =['a', 'b', 'c', 'd', 'e', 'f', 'g']  
a = pd.Series(Data, index = index) 
print(a)

 #output
 
 1    a
3    b
4    c
5    d
6    e
2    f
9    g
dtype: object
 

Creating a series with a dictionary


import pandas as pd  
# import Pandas 
  
# Generate the series with a dictionary data
dct ={'red':1, 'blue':2, 'green':3, 'orange':4, 'purple':5}
a = pd.Series(dct) 
print(a)

#output

red       1
blue      2
green     3
orange    4
purple    5
dtype: int64

Creating a series with Numpy.ndarray


import pandas as pd  
import numpy as np
# import Pandas 
  
# Generate the series with numpy
arr=np.array([10, 20, 30, 40])
a = pd.Series(arr) 
print(a)

#output
0    10
1    20
2    30
3    40
dtype: int64

Or, we can provide the index explicitly,

import pandas as pd  
import numpy as np
# import Pandas 
  
# Generate the series with numpy
arr=np.array([10, 20, 30, 40])
index=['a','b','c','d']
a = pd.Series(arr, index=index) 
print(a)

#output
a    10
b    20
c    30
d    40
dtype: int64

Create a series with a scaler


import pandas as pd  
# import Pandas 
  
# Generate the series with a scaler
index=['a','b','c','d']
a = pd.Series(5.0, index=index) 
print(a)

#output
a    5.0
b    5.0
c    5.0
d    5.0
dtype: float64

Accessing element by index


The elements can be accessed by the label or index position.

import pandas as pd  
import numpy as np
# import Pandas 
  
index=['a','b','c','d']
arr=np.array([20, 50, 60, 80])
s = pd.Series(arr, index=index) 
print(s['b']) #accessing elements in a series
print(s[0]) #accessing elements in a series

#output
50
20

Series Object Attributes


These attributes return information about the series. For example

  • Series.T returns the transpose, It is basically its own definition.
  • Series.array returns the ExtensionArray of the data backing this Series or Index
  • Series.shape defines a tuple of shape of the data.
  • Series.dtype defines the data type of the data.
  • Series.size defines the size of the data.
  • Series.index defines the index of the Series.
  • Series.empty defines True if Series object is empty, otherwise returns false.
  • Series.hasnans returns a boolean value True if there are any NaN values, otherwise returns false.
  • Series.nbytes defines the number of bytes in the data.
  • Series.ndim defines the number of dimensions in the data.
  • Series.is_monotonic returns a boolean value if the values in the object are monotonic_increasing.
  • Series.is_monotonic_decreasing returns a boolean value if values in the object are monotonically decreasing.
  • Series.is_monotonic_increasing returns a boolean value if values in the object are monotonically increasing.
  • Series.at can be used to access a single value for a row/column label pair.
  • Series.itemsize defines the size of the datatype of item.

import pandas as pd  
import numpy as np
# import Pandas 
  
index=['a','b','c','d']
arr=np.array([20, 50, 60, 80])
s = pd.Series(arr, index=index)

print(s.index)   
print(s.values)
print(s.ndim)
print(s.dtype)

#output
Index(['a', 'b', 'c', 'd'], dtype='object')
[20 50 60 80]
1
int64


Series Object methods


There are several methods provides to perform several operations using the series.

Series.map()

The Series.map() method returns the values from two series that having a common column.

Series.std()

To get the standard deviation of the given set of numbers, DataFrame, column, and rows.

Series.to_frame()

To transform a series object to a dataframe.

Series.value_counts()

This method returns a Series having the counts of unique values.



Monday, June 29, 2020

Python pandas introduction

Python pandas introduction


The 'pandas' is one of the most popular, open-source Python package used for data analysis and manipulation. It was developed by Wes McKinney in 2008. This is the abbreviation of the Panel Data System. We can organize the data in two-dimensional tabular forms. Pandas is built on the top of Numpy






The pandas is an efficient, powerful, flexible, high performance, and easy to use data analysis and manipulation tool. Pandas provide us the power to work with data from comprehensive types of resources like .csv, .tsv, excel sheets, and webpages.

The pandas is a very suitable tool for the data scientists because it can be used for
  • Managing data
  • Cleaning data
  • Analyzing data
  • Modeling data
  • Organizing the data in the desired form to plot the results or display the data in tabular form.

pandas is an appropriate choice for various types of data, such as
  • The data kept in some tabular format (Excel spreadsheets, SQL table, etc.)
  • The data can be in ordered and unordered.
  • The data can be arbitrary matrix data (homogeneously typed or heterogeneous) with row and column labels 
  • The data in any other format of observational/statistical data sets. The data is not required to be labeled at all to be kept in a pandas data structure.

pandas Installation


Pandas is part of the Anaconda distribution and can be installed with Anaconda or Miniconda,

conda install pandas
 Or it can be installed using pip,

pip install pandas


Key features of pandas


Few key features of pandas are,

  • All the missing data in floating point, as well as non-floating point data, is handled very easily by pandas. This data is represented as NaN.
  • The size of a DataFrame is mutable, the columns can be added or removed.
  • Automatic and clear-cut data alignment
  • Pansdas provides a strong and versatile set of functions to execute split-apply-combine operations on data sets to aggregate and transform the data
  • Intelligent label-based slicing, fancy indexing, and subsetting of large data sets
  • Automatic merging and joining data sets
  • Flexible reshaping and pivoting of data sets
  • Hierarchical labeling of axes
  • Flavorsome IO tools for loading data Time series-specific functionality


Main components of pandas


Series and DataFrames are the two main components of pandas. A Series represents a column containing the data, and a DataFrame represents a multi-dimensional table composed of a set of multiple Series.


Saturday, June 27, 2020

Basic types in TypeScript

Basic Types in TypeScript


TypeScript is a strongly typed language, it supports different types. The validity of the given values is checked by the Type System. The type of the variable is declared at the start and this type will be maintained through the execution otherwise it will result in a compile-time error.

We can work with simple data types, such as numbers, strings, objects, Booleans, etc.

All of the JavaScript data types are supported by TypeScript along with the enumeration data type.


Boolean


The boolean is a basic datatype holding true/false value, for example

 

let finished: boolean = false;


Number


Similar to JavaScript, the numbers in TypeScript are floating-point values. These floating-point numbers get the type number. In addition to hexadecimal and decimal literals, It also supports binary and octal literals described in ECMAScript 2015.
let a: number = 16;
let b: number = 0xf01d;
let c: number = 0b1110;
let d: number = 0o644;


String 


The string data types are used to represent the text data. Similar to JavaScript strings, TypeScript also uses double quotes (") or single quotes (') to enclose the string data.

let brand: string = "Honda";


We can use template strings, those can span multiple lines with embedded expressions. Template strings are enclosed by the backtick/backquote (`) character, and the embedded expressions are represented in the form ${ expression }. For example,

let fName: string = `James Bond`;
let age: number = 29;
let sentence: string = `I am Bond, ${ fullName }.
i am ${ age + 1 } years old next week.`;

Arrays 


Similar to JavaScript arrays, we can declare and work with arrays containing values. The types of array can be declared in one of two ways. First, by using the type of the items followed by [] to represent an array containing that element type.

let nums: number[] = [10, 20, 30, 40];
The second way is by using Generic types.

let nums: Array<number> = [10, 20, 30, 40];

Tuple 


Tuple enables to represent an array with a fixed number of items whose types are known, but not required to be the same. For example, to represent a value as a pair of a string and a number, we can write,

// Declare a tuple type
let t: [string, number];
// Initialize it
t = ["hello", 10]; // OK
// Initialize it incorrectly
t = [10, "hello"]; // Error

Enum 


Enums are a useful addition to the standard set of data types available in JavaScript. The purpose of the enums is the same as in languages like C#, as they provide a way of giving more friendly names to sets of numeric values.

enum Brand {Google = 1, Apple, Samsung}
let brandName: string = Brand[2];

console.log(brandName); // writes 'Apple' as its value is 2 above

Any


Sometimes, it possible that the type of the variable is not known, and the values are generated by any dynamic content like some random user or third party library. In such a situation the type of the variable can be declared as ‘any’.

const isFinished: any = 4;
isFinished = "Not yet"; // String
isFinished = True; // boolean

void 


The void is generally used as the return type of a function which does not return a value. A void type represents that variable does not have a type. The behavior of the void is just opposite to ‘any’.

function showMessage(): void {
    console.log("Welcome Message");
}

It is not fruitful to declare a variable of type void because they can only be assigned null or undefined.

const unfruitful: void = undefined;
unfruitful = null;


Null and Undefined


undefined and null are types names actually have their own type names Null and undefined respectively. However, they are very useful themselves like void,

const v1: undefined = undefined;
const v2: null = null;


Never


The never type are used as the type of values that never occur. For example, never is the return type for a function expression or an arrow function expression that always throws an exception or one that never returns.

A variable can also obtain the type never when narrowed by any type guards that can never be true. The never type is a subtype of, and assignable to, every type; however, no type is a subtype of, or assignable to, never (except never itself). In fact, ‘any’ cannot be assigned to a never.


Object 


The user-defined types can be represented by the object (types excluding number, Boolean, string, symbol, bigint, null, undefined).


Sunday, June 21, 2020

JavaScript ECMA Script 6

JavaScript ECMA Script 6 - ECMA Script 2015


JavaScript


JavaScript is a high-level, prototype-based, dynamic, and interpreted programming language designed originally for web browsers.

ECMAScript implementation


ECMA(stands for European Computer Manufacturers Association) is a non-profit standards organization working in the field of information and communication systems.

ECMAScript (ES) is a scripting-language specification standardized by ECMA International in ECMA-262 and ISO/IEC 16262. There various popular implementations of this language, such as JavaScript, JScript, and ActionScript having large acceptance for the client-side scripting on the Web.

ES2015 (ES6) is the latest version of ECMAScript.



ES6 Goals 


  • To fix some of the ES5 issues 
  • To provide backward compatibility (ES5 code is valid in ES6)
  • Modern syntax
  • Better suited for big applications(Scalability) 
  • New features in the standard library

ECMA Script New features


Several new features were introduced by the ES6. Some of them are

  • Introduced let
  • Introduced const
  • Introduced Arrow Functions
  • Introduced JavaScript Classes
  • Default parameter values(Extended parameter handling)
  • Introduced Array.find()
  • Introduced Array.findIndex()
  • Enhanced Regular expressions
  • Exponentiation (**) (EcmaScript 2016)

let


The "let" keyword helps us to enable the resolution between the two variables. We can declare variables with block scope.

const


The const keyword allows us to create JavaScript variables with constant values. A const cannot be reassigned and a const keyword creates the read the only reference to value. If we have assigned a primitive value to const than it can not be changed.


Arrow function


JavaScript arrow functions are like lambda functions in Python or blocks in Ruby. JavaScript arrow functions are anonymous functions having special syntax. JavaScript arrow functions accept a fixed number of arguments and operate in the function or block of code within which they are defined.

The basic syntax of an arrow function is

(arg1, arg2, ... argN) => { 

// body of the function

}

JavaScript Classes


Javascript classes are a syntactical wrapper around the existing prototype-based inheritance. The keyword class is used to create a class that is followed by the name of the class.

For example,

class Rectangle //class declaration
{//class body starts
    constructor(ht,wd)//Constructor
            {
                this.ht=ht;//class properties
                this.wd=wd;
            }
}//class body ends

Default Parameters


We can pass default parameters to the functions, for example

function add(a, b = 10) {
  // b is 10 if not passed or undefined
  return a + b;
}
add(7); // will return 17

Array.find() 


The Array.find() returns the value of the first array element that passes a test function. For example,

var nums = [14, 19, 16, 25, 29];
var fst = nums.find(myFunction);

document.getElementById("demo").innerHTML = "First number over 20 is " + fst;

function myFunction(value, index, array) {
  return value > 20;
}
In the code above, 25 is the first number that is greater than 20.

Array.findIndex()


This method works similar to Array.find() except, it returns the index of the matched element. For example,

var nums = [14, 19, 16, 25, 29];
var fst = nums.findIndex(myFunction);

document.getElementById("demo").innerHTML = "First number over 20 has index " + fst;

function myFunction(value, index, array) {
  return value > 20;
}
// Output
//First number over 20 has index 3


Introduction to new properties and methods to the number object


Following new properties to JavaScript number object are  added in ECMA Script 6,

  • EPSILON
  • MIN_SAFE_INTEGER
  • MAX_SAFE_INTEGER
The following new methods are added to the number object.

  • Number.isInteger()
  • Number.isSafeInteger()

Exponentiation Operator


The exponentiation operator (**) was introduced in ECMA Script 6. For example

let a = 4;
document.getElementById("demo").innerHTML = a ** 2;

//Output
//16

Improved Regular Expression 


Sticky Matching introduced with regular expression, that keeps the matching position sticky between matches and this way supports efficient parsing of arbitrary long input strings, even with an arbitrary number of distinct regular expressions.



Saturday, June 20, 2020

TypeScript installation and create first application

TypeScript Installation And Create First Application


TypeScript installation


Two main ways to install the TypeScript,


Visual Studio 2017 and Visual Studio 2015 Update 3 include TypeScript by default. We can download and install the TypeScript from this link.

npm install -g typescript
To check the installation version, the following command can be used,

tsc -version

Creating first TypeScript Application


Write the following code in a file with the .ts extension (let the name be message.ts).

function showMessage(msg) {
    return "Welcome to " + msg;
}

let msg = "TypeScript";

console.log(showMessage(msg));

Compile the .ts code


We can compile the above code using the following command,

tsc message.ts
A new file with name message.js is created, with the following equivalent JavaScript content.

function showMessage(msg) {
    return "Welcome to " + msg;
}
var msg = "TypeScript";
console.log(showMessage(msg));

Execute this file using the following command,

node message.js

typescript compilation


The .ts file is eventually transpired into a .js file, that can be run on any browser, host, or OS.

Type Annotations


Both the files above, message.ts, and message.js are exactly the same. We can add type annotations to this function message. The Type Annotations in TypeScript are lightweight ways to store the desired contract of the function or variable. In our message function, we intend to take in a string parameter.

Just add a : string type annotation to the ‘msg’ function argument,

function showMessage(msg : String) {
    return "Welcome to " + msg;
}

let msg = "TypeScript";

console.log(showMessage(msg));
Passing argument having type other than String will result in an error on the compilation for the above code.

JavaScript TypeScript

TypeScript


JavaScript

JavaScript was developed initially as a client-side programing language. Programmers realized that JavaScript can be used as a server-side programming language too. JavaScript had a lot of potentials, but still, it lacks the ability to maintain large and complex programs. JavaScript lacks various structuring mechanisms like static typing, classes, modules, and interfaces.

TypeScript


TypeScript is an open-source programming language built over JavaScript and maintained by Microsoft. TypeScript is a typed superset of JavaScript that is ultimately compiled into regular JavaScript. It allows developers to create scalable and maintainable JavaScript development. It can be run on any browser, host, or OS.

typescript javascript


TypeScript opted for the same JavaScript syntax and semantics. We can use existing JavaScript code, integrate popular JavaScript libraries, and call TypeScript code from JavaScript. 


typescript


TypeScript code is compiled into a clean, simple JavaScript code that can be executed on any browser, in Node.js, or in any JavaScript engine supporting ECMAScript 3 (or newer). The browsers do not understand the Typescript(.ts extension) directly, so first this code is compiled and transformed into JavaScript (.js Extension). This code is known as trans-piled code. This code is eventually run by the browsers.


Features of TypeScript


TypeScript has following features
 
  • TypeScript supports standard JavaScript code with static typing
  • Zero cost: Static types completely disappear at run-time
  • TypeScript supports encapsulation through classes, modules, and interfaces
  • TypeScript supports constructors, properties, and functions (public, private)
  • TypeScript supports enums, lambdas and generics support
  • Intellisense and syntax checking can be incorporated with TypeScript
  • Designed for large scale development
  • TypeScript allows the support for optional parameter function that is not supported by JavaScript.


TypeScript code is compiled; it means the errors can be detected at the development phase, it reduces the chances of the run-time errors significantly in comparison to the JavaScript as it is an interpreted language.

TypeScript is strongly-typed (known as static typing), it allows for checking type correctness at compile time. This feature is absent in JavaScript. TypeScript is nothing but JavaScript with some improvements over ES6 JavaScript features. It may not be supported by few browsers but the TypeScript compiler can compile the .ts files into ES3,ES4 and ES5 also.

Friday, June 19, 2020

ReactJS inline CSS

ReactJS CSS


Inline stylesheet ReactJS


The inline stylesheet(CSS) is one of the ways to apply styles to any HTML page. In React JSX, JavaScript expressions are placed within curly brackets. Since, the inline style rules are also written within the curly brackets, so we need to write inline style rules inside two sets of curly brackets {{}}.

for example,

class SimpleHeader extends React.Component {
  render() {
    return (
      <div>
      <h1 style={{color: "red"}}>Inline Style</h1>
      <p>Welcome to ReactJS</p>
      </div>
    );
  }

ReactDOM.render(<div><SimpleHeader/></div>,document.getElementById('root'));

camelCased Property Names 

Since the inline CSS is written in a JavaScript object, properties with two names, like background-color, must be written in camel-cased syntax,

class SimpleHeader extends React.Component {
  render() {
    return (
      <div>
      <h1 style={{color: "red", backgroundColor:'lightgreen'}}>Inline Style</h1>
      <p>Welcome to ReactJS</p>
      </div>
    );
  }
}
ReactDOM.render(<div><SimpleHeader/></div>,document.getElementById('root') );

Style rules withing JavaScript Object


We can create a JavaScript object containing style information and use it as attribute in JSX. For example,

class SimpleHeader extends React.Component {
  render() {
    const hstyle= {
      color: "white",
      backgroundColor: "DodgerBlue",
      padding: "10px",
      fontFamily: "Arial"
    };
    return (
      <div>
      <h1 style={hstyle}>Style Example</h1>
      <p>Welcome to ReactJS</p>
      </div>
    );
  }
}
ReactDOM.render(<div><SimpleHeader/></div>,document.getElementById('root') );

The result will appear as,


reactjs inline style



The above can also be written as,

function SimpleHeader()  
{
    const hstyle= {
      color: "white",
      backgroundColor: "DodgerBlue",
      padding: "10px",
      fontFamily: "Arial"
    };
    return (
      <div>
      <h1 style={hstyle}>Style Example</h1>
      <p>Welcome to ReactJS</p>
      </div>);
    
}
ReactDOM.render(<div><SimpleHeader/></div>,document.getElementById('root'));


External CSS


The style rules can be written inside an external .css file and it can be imported later for the use. For example, we can create App.css having the following content,

#sh {
  background-color: #282c34;
  color: orange;
  padding: 40px;
  font-family: Arial;
  text-align: center;
}
It can now be imported to the application as,

import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';

function SimpleHeader()  
{
    return (
      <div id='sh'>
      <h1>Style Example</h1>
      <p>Welcome to ReactJS</p>
      </div>);
    
}
ReactDOM.render(<div><SimpleHeader/></div>,document.getElementById('root') );

The results will appear as,



reactjs external stylesheet


CSS Modules


Another very simple and convenient way to add styles to the React components is the CSS modules. These modules are placed in separate files. 

The CSS placed inside a module is available only for the component that imported it, and we need not take care of the about naming conflicts.  We can create a CSS module with the .module.css extension (e.g. sh.module.css), and place the following code within this file.

.sh {
  background-color: #282c34;
  color: DodgerBlue;
  padding: 40px;
  font-family: Arial;
  text-align: center;
}

Now, we can import the style in our code as,

import React from 'react';
import ReactDOM from 'react-dom';
import styles from './sh.module.css'; 

function SimpleHeader()  
{
    return (
      <div className={styles.sh}>
      <h1>Style Example</h1>
      <p>Welcome to ReactJS</p>
      </div>);
    
}
ReactDOM.render(<div><SimpleHeader/></div>,document.getElementById('root') );

Python Generators

Python Generators


Generator


Generators are a simple and powerful tool for creating iterators. Generator functions are a special kind of functions that enable us to declare a function that works similar to an iterator. It can be used in a for-loop. It looks like a regular Python function except that it contains yield expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the next() function.

Every time next() is called on a generator, it resumes where it left off. It means a generator function can maintain an internal state every time it is invoked.

for example,

def inverse(message):
    for index in range(len(message)-1, -1, -1):
        yield message[index]
        
for char in inverse('Python'):
  print(char)

#Output
n
o
h
t
y
P

Why generators?


  • We can perform all operations that can be done using a class-based iterator. The reason behind the compactness of a generator is that __iter__() and __next__() methods are produced automatically.
  • One of the most important aspects of generators is that the local variables and execution state are saved implicitly between the calls. This makes the generator functions easy to write and more transparent than using instance variables like self.index and self.data.
  • A generator automatically raises StopIteration, when it is terminated.

All these features make it easier to write iterators than writing a regular Python function.


Generator Expressions



We can sometimes briefly write simple generators as expressions only. The syntax appears to the list comprehensions, except the parenthesis are used in place of square brackets. Generator expressions are particularly in situations where the generator is used immediately by the enclosing function. However, generator expressions may seem compact, but they are less versatile than the full generator definitions. Generator expressions are more memory efficient in comparison to the list comprehensions.

For example,

print(sum(i*i*i for i in range(10))) #sum of cubes

#Output
2025

x = [5, 7, 9]
y = [3, 4, 5]
dp=sum(i*j for i,j in zip(x,y))
print(dp)

#Output
88

print(max(i for i in [10,7,9,5,12,14])) 

#output
14

Wednesday, June 17, 2020

Node.js JSON Read Write

Node.js JSON Read Write


Node.js is a JavaScript runtime environment. It is an open-source, cross-platform, asynchronous runtime environment capable of running JavaScript code outside a web browser. It is widely accepted and used in developing APIs and microservices by various organizations.

JSON means for JavaScript Object Notation. JSON is an open standard lightweight format for data interchange. JSON is a format for storing and transporting data consisting of comma-separated attribute-value pairs and array data types. JSON is commonly used to send the information from a server to a web page. 

json syntax



JSON is one of the best ways to interchange data between applications written in different languages. It is very useful to know about how to read and write JSON data to a file in Node.js.

We are discussing, how to handle JSON data with Node in this tutorial. 

Read JSON data using require() method


The easiest way to read a JSON File is require() method. For example, we have a file (named person.json) containing the following data.

[ 
{ 
	"name": "Steve", 
	"age": 31, 
	"skill": ["Java", "PHP", "Python"] 
}, 
{ 
	"name": "Alex", 
	"age": 27, 
	"skill": ["Perl", "Dart", "JavaScript"] 
} 
] 

We can read the data from this file using the following code(named index.js).

const person = require("./person"); 
  
console.log(person); 

The require('path/to/file/filename') method is used. Execute the code using the following command.

node index.js
The results will appear as,

C:\Users\user\Desktop\brackets>node index.js
[
  { name: 'Steve', age: 31, skill: [ 'Java', 'PHP', 'Python' ] },
  { name: 'Alex', age: 27, skill: [ 'Perl', 'Dart', 'JavaScript' ] }
]

Using the fs module 


Read the file


The fs module can also be used to read the JSON file. The fs module returns a file content in a string format. This string can be converted into JSON format by using JSON.parse() in-built method.

var fs = require("fs"); 
   
// Reading person.json file 
fs.readFile("person.json", function(err, data) { 
      
    // handle errors 
    if (err) throw err; 
   
    // Converting to JSON 
    const users = JSON.parse(data); 
      
    console.log(users);  
});

Write to the file


A new user can be added to the person.json file. We can read the file, add data using .push() method, and write the new data to the file using JSON.stringify() method to convert data into a string.

var fs = require("fs"); 

// Read the JSON file 
var person = require("./person"); 

// Define new person
var newperson = { 
	name: "David", 
	age: 33, 
	language: ["TypeScript", "HTML", "Node.js"] 
}; 

// Adding new person to person.json 
person.push(newperson); 

// Write data to the file 
fs.writeFile("person.json", JSON.stringify(person), err => { 
	
	// Handle errors 
	if (err) throw err; 

	// on success prompt success message
	console.log("Data added");  
}); 
The person.json will be appended with new person data.

[
{"name":"Steve","age":31,"skill":["Java","PHP","Python"]},
{"name":"Alex","age":27,"skill":["Perl","Dart","JavaScript"]},
{"name":"David","age":33,"language":["TypeScript","HTML","Node.js"]}
]