TypeScript

install and config with npm

npm install typescript -D -g
npm link typescript
npm install -D ts-node
npm install -P @types/node

add scripts to package.json

"scripts": {
    "start": "node --inspect=5858 -r ts-node/register ./tutorial.ts",
    "build": "tsc  && copyfiles -U 1 ./**/*.env ./dist"
  }

build script convert all ts files to js and move it to ./dist folder

copyfiles is a tool to help you to move files to destination folder

npm install -D copyfiles

tsconfig.json file  in a directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project.

{
    "compilerOptions": {
        "module": "commonjs",
        "moduleResolution": "node",
        "pretty": true,
        "sourceMap": true,
        "target": "es6",
        "outDir": "./dist",
        "baseUrl": ".",
    },
    "include": [
        "./**/*"
    ],
    "exclude": [
        "node_modules",
        ".vscode"
    ]
}

so once you call tsc command it will build all files specified by tsconfig.json to target

let var1:string|number=44;
let var2:object={};
let var3:any;
let var4:void;//null or undefined
//===============================
let strArr:string[];//accept only array of string
let strArr2:[string,number];//tuple string,number
let strArr3:Array<string>;
//========================
let any:any;//take any value
let fun:(a: string) => void;//function type

TypeScript interface

interface Options {
  color: string;
  volume: number;
}
let options = {} as Options;
options.color = "red";
options.volume = 11;
interface User {
  name: string;
  id: number;
}
class UserAccount {
  name: string;
  id: number;
  constructor(name: string, id: number) {
    this.name = name;
    this.id = id;
  }
}
const user: User = new UserAccount("Murphy", 1);
interface  A{
    val1:string;
    val2:number;
}
class AA{
    val1:string;
    val2:number;
    val3:string;
    constructor(name:string,age:number) {
        this.val1=name;
        this.val2=age;
        this.val3=name+age;
    }
}
let val:A=new AA("hello",12);
console.log(val);

classes and abstract classes

interface IPerson {
    name: string;
    display():void;
}

interface IEmployee {
    empCode: number;
}

class Employee implements IPerson, IEmployee {
    empCode: number;
    name: string;
    
    constructor(empcode: number, name:string) {
        this.empCode = empcode;
        this.name = name;
    }
    
    display(): void {
        console.log("Name = " + this.name +  ", Employee Code = " + this.empCode);
    }
}

let per:IPerson = new Employee(100, "Bill");
per.display(); // Name = Bill, Employee Code = 100

let emp:IEmployee = new Employee(100, "Bill");
emp.display(); //Compiler Error: Property 'display' does not exist on type 'IEmployee'
class Car {
    name: string;
        
    constructor(name: string) {
        this.name = name;
    }
    
    run(speed:number = 0) {
        console.log("A " + this.name + " is moving at " + speed + " mph!");
    }
}

class Mercedes extends Car {
    
    constructor(name: string) {
        super(name);
    }
    
    run(speed = 150) {
        console.log('A Mercedes started')
        super.run(speed);
    }
}

class Honda extends Car {
    
    constructor(name: string) {
        super(name);
    }
    
    run(speed = 100) {
        console.log('A Honda started')
        super.run(speed);
    }
}

let mercObj = new Mercedes("Mercedes-Benz GLA");
let hondaObj = new Honda("Honda City")

mercObj.run();  // A Mercedes started A Mercedes-Benz GLA is moving at 150 mph!
hondaObj.run(); // A Honda started A Honda City is moving at 100 mph!
class StaticMem {  
   static num:number; 
   
   static disp():void { 
      console.log("The value of num is"+ StaticMem.num) 
   } 
} 

StaticMem.num = 12     // initialize the static variable 
StaticMem.disp()      // invoke the static method
abstract class Person {
    abstract name: string;

    display(): void{
        console.log(this.name);
    }
}

class Employee extends Person { 
    name: string;
    empCode: number;
    
    constructor(name: string, code: number) { 
        super(); // must call super()
        
        this.empCode = code;
        this.name = name;
    }
}

let emp: Person = new Employee("James", 100);
emp.display(); //James
class StaticMem {  
   static num:number; 
   
   static disp():void { 
      console.log("The value of num is"+ StaticMem.num) 
   } 
} 

StaticMem.num = 12     // initialize the static variable 
StaticMem.disp()      // invoke the static method

namespace

namespace SomeNameSpaceName { 
   export interface ISomeInterfaceName {      }  
   export class SomeClassName {      }  
} 
SomeNameSpaceName.SomeClassName;

as keyword

const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;

type aliases

type func=(a: string) => void;
type Point = {
  x: number;
  y: number;
};
 
// Exactly the same as the earlier example
function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
 
printCoord({ x: 100, y: 100 });

MongoDB

RDBMSMongoDB
DatabaseDatabase
TableCollection
Tuple/RowDocument
columnField
Table JoinEmbedded Documents
Primary KeyPrimary Key (Default key _id provided by MongoDB itself)
{
   _id: ObjectId(7df78ad8902c)
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100, 
   comments: [	
      {
         user:'user1',
         message: 'My first comment',
         dateCreated: new Date(2011,1,20,2,15),
         like: 0 
      },
      {
         user:'user2',
         message: 'My second comments',
         dateCreated: new Date(2011,1,25,7,45),
         like: 5
      }
   ]
}

Embedded Data Model

In this model, you can have (embed) all the related data in a single document, it is also known as de-normalized data model.

For example, assume we are getting the details of employees in three different documents namely, Personal_details, Contact and, Address, you can embed all the three documents in a single one

{
	_id: ,
	Emp_ID: "10025AE336"
	Personal_details:{
		First_Name: "Radhika",
		Last_Name: "Sharma",
		Date_Of_Birth: "1995-09-26"
	},
	Contact: {
		e-mail: "radhika_sharma.123@gmail.com",
		phone: "9848022338"
	},
	Address: {
		city: "Hyderabad",
		Area: "Madapur",
		State: "Telangana"
	}
}

Normalized Data Model

In this model, you can refer the sub documents in the original document, using references. For example, you can re-write the above document in the normalized model as:

Employee:

{
	_id: <ObjectId101>,
	Emp_ID: "10025AE336"
}

Personal_details:

{
	_id: <ObjectId102>,
	empDocID: " ObjectId101",
	First_Name: "Radhika",
	Last_Name: "Sharma",
	Date_Of_Birth: "1995-09-26"
}

Contact:

{
	_id: <ObjectId103>,
	empDocID: " ObjectId101",
	e-mail: "radhika_sharma.123@gmail.com",
	phone: "9848022338"
}

Address:

{
	_id: <ObjectId104>,
	empDocID: " ObjectId101",
	city: "Hyderabad",
	Area: "Madapur",
	State: "Telangana"
}
show dbs; //show all databases
use db;//select database
db;//current database
db.movie.insert({"name":"tutorials point"})//insert document to collection
db.dropDatabase()//remove database
db.createCollection("mycollection")//create collection
db.COLLECTION_NAME.drop()//remove collection
show databases // display all databases
use database //select or create database
show collections // display all collections
db.post.insert([
	{
		title: "MongoDB Overview",
		description: "MongoDB is no SQL database",
		by: "tutorials point",
		url: "http://www.tutorialspoint.com",
		tags: ["mongodb", "database", "NoSQL"],
		likes: 100
	},
	{
	title: "NoSQL Database",
	description: "NoSQL database doesn't have tables",
	by: "tutorials point",
	url: "http://www.tutorialspoint.com",
	tags: ["mongodb", "database", "NoSQL"],
	likes: 20,
	comments: [
		{
			user:"user1",
			message: "My first comment",
			dateCreated: new Date(2013,11,10,2,35),
			like: 0
		}
	]
}
])
db.empDetails.find(
	{
		$nor:[
			40
			{"First_Name": "Radhika"},
			{"Last_Name": "Christopher"}
		]
	}
)
db.COLLECTION_NAME.find(
	{
		$NOT: [
			{key1: value1}, {key2:value2}
		]
	}
)
db.empDetails.find( { "Age": { $not: { $gt: "25" } } } )
OperationSyntaxExampleRDBMS Equivalent
Equality{<key>:{$eg;<value>}}db.mycol.find({“by”:”tutorials point”}).pretty()where by = ‘tutorials point’
Less Than{<key>:{$lt:<value>}}db.mycol.find({“likes”:{$lt:50}}).pretty()where likes < 50
Less Than Equals{<key>:{$lte:<value>}}db.mycol.find({“likes”:{$lte:50}}).pretty()where likes <= 50
Greater Than{<key>:{$gt:<value>}}db.mycol.find({“likes”:{$gt:50}}).pretty()where likes > 50
Greater Than Equals{<key>:{$gte:<value>}}db.mycol.find({“likes”:{$gte:50}}).pretty()where likes >= 50
Not Equals{<key>:{$ne:<value>}}db.mycol.find({“likes”:{$ne:50}}).pretty()where likes != 50
Values in an array{<key>:{$in:[<value1>, <value2>,……<valueN>]}}db.mycol.find({“name”:{$in:[“Raj”, “Ram”, “Raghu”]}}).pretty()Where name matches any of the value in :[“Raj”, “Ram”, “Raghu”]
Values not in an array{<key>:{$nin:<value>}}db.mycol.find({“name”:{$nin:[“Ramu”, “Raghav”]}}).pretty()Where name values is not in the array :[“Ramu”, “Raghav”] or, doesn’t exist at all
{"x":{"$exists":true}} // = {"x":{"$ne":null}}

update and Save()

db.mycol.update({'title':'MongoDB Overview'},
   {$set:{'title':'New MongoDB Tutorial'}},{multi:true})
>db.mycol.save( //for insert or update
   {
      "_id" : ObjectId("507f191e810c19729de860ea"), 
		"title":"Tutorials Point New Topic",
      "by":"Tutorials Point"
   }
)
WriteResult({
	"nMatched" : 0,
	"nUpserted" : 1,
	"nModified" : 0,
	"_id" : ObjectId("507f191e810c19729de860ea")
})
>db.mycol.find()
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point New Topic",
   "by":"Tutorials Point"}
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"NoSQL Overview"}
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point Overview"}
db.empDetails.updateOne(
	{First_Name: 'Radhika'},
	{ $set: { Age: '30',e_mail: 'radhika_newemail@gmail.com'}}
)
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }
db.empDetails.updateMany(
	{Age:{ $gt: "25" }},
	{ $set: { Age: '00'}}
)
db.mycol.remove({'title':'MongoDB Overview'})
WriteResult({"nRemoved" : 1})
db.mycol.find()
{"_id" : ObjectId("507f191e810c19729de860e2"), "title" : "NoSQL Overview" }
{"_id" : ObjectId("507f191e810c19729de860e3"), "title" : "Tutorials Point Overview" }

limit and sort

db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL Overview"}
db.COLLECTION_NAME.find().sort({KEY:1})

indexing

db.mycol.createIndex({"title":1,"description":-1})
db.mycol.dropIndexes({"title":1,"description":-1})
db.members.createIndex( { "user_id": 1 }, { unique: true } )
db.COLLECTION_NAME.getIndexes()
db.COLLECTION_NAME.dropIndexes()
ParameterTypeDescription
backgroundBooleanBuilds the index in the background so that building an index does not block other database activities. Specify true to build in the background. The default value is false.
uniqueBooleanCreates a unique index so that the collection will not accept insertion of documents where the index key or keys match an existing value in the index. Specify true to create a unique index. The default value is false.
namestringThe name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order.
sparseBooleanIf true, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). The default value is false.
expireAfterSecondsintegerSpecifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection.
weightsdocumentThe weight is a number ranging from 1 to 99,999 and denotes the significance of the field relative to the other indexed fields in terms of the score.
default_languagestringFor a text index, the language that determines the list of stop words and the rules for the stemmer and tokenizer. The default value is English.
language_overridestringFor a text index, specify the name of the field in the document that contains, the language to override the default language. The default value is language.

projection

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  dbo.collection("customers").find({}, { projection: { _id: 0, name: 1, address: 1 } }).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

aggregate() Method

{
   _id: ObjectId(7df78ad8902c)
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by_user: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
},
{
   _id: ObjectId(7df78ad8902d)
   title: 'NoSQL Overview', 
   description: 'No sql database is very fast',
   by_user: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 10
},
{
   _id: ObjectId(7df78ad8902e)
   title: 'Neo4j Overview', 
   description: 'Neo4j is no sql database',
   by_user: 'Neo4j',
   url: 'http://www.neo4j.com',
   tags: ['neo4j', 'database', 'NoSQL'],
   likes: 750
}

//similar to count method
db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{ "_id" : "tutorials point", "num_tutorial" : 2 }
{ "_id" : "Neo4j", "num_tutorial" : 1 }

Following are the possible stages in aggregation framework −

  • $project − Used to select some specific fields from a collection.
  • $match − This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage.
  • $group − This does the actual aggregation as discussed above.
  • $sort − Sorts the documents.
  • $skip − With this, it is possible to skip forward in the list of documents for a given amount of documents.
  • $limit − This limits the amount of documents to look at, by the given number starting from the current positions.
  • $unwind − This is used to unwind document that are using arrays. When using an array, the data is kind of pre-joined and this operation will be undone with this to have individual documents again. Thus with this stage we will increase the amount of documents for the next stage.
ExpressionDescriptionExample
$sumSums up the defined value from all documents in the collection.db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$sum : “$likes”}}}])
$avgCalculates the average of all given values from all documents in the collection.db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$avg : “$likes”}}}])
$minGets the minimum of the corresponding values from all documents in the collection.db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$min : “$likes”}}}])
$maxGets the maximum of the corresponding values from all documents in the collection.db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$max : “$likes”}}}])
$pushInserts the value to an array in the resulting document.db.mycol.aggregate([{$group : {_id : “$by_user”, url : {$push: “$url”}}}])
$addToSetInserts the value to an array in the resulting document but does not create duplicates.db.mycol.aggregate([{$group : {_id : “$by_user”, url : {$addToSet : “$url”}}}])
$firstGets the first document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.db.mycol.aggregate([{$group : {_id : “$by_user”, first_url : {$first : “$url”}}}])
$lastGets the last document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.db.mycol.aggregate([{$group : {_id : “$by_user”, last_url : {$last : “$url”}}}])

distinct query

db.Files.distinct("originalName",{"filament":"PLA"})

Nodejs express

Express Overview

Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications. Following are some of the core features of Express framework −

  • Allows to set up middlewares to respond to HTTP Requests.
  • Defines a routing table which is used to perform different actions based on HTTP Method and URL.
  • Allows to dynamically render HTML Pages based on passing arguments to templates.

Installing Express

Firstly, install the Express framework globally using NPM so that it can be used to create a web application using node terminal.

$ npm install express --save

The above command saves the installation locally in the node_modules directory and creates a directory express inside node_modules. You should install the following important modules along with express −

  • body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
  • cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
  • multer − This is a node.js middleware for handling multipart/form-data.
$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save

Routing

var express = require('express');
var app = express();

app.get('/', function (req, res) {
   res.send('Hello World');
})

app.get(/a/, function (req, res) {//any url contains a
  res.send('/a/')
})

app.get('/name/:name',function (req,res){//req.params={name:"mohammed"}
    res.send("hello world");
});

var server = app.listen(8081, function () {
   var host = server.address().address;
   var port = server.address().port;
   
   console.log("Example app listening at http://%s:%s", host, port)
})
app.route('/book')
  .get(function (req, res) {
    res.send('Get a random book')
  })
  .post(function (req, res) {
    res.send('Add a book')
  })
  .put(function (req, res) {
    res.send('Update the book')
  })

static files

Express provides a built-in middleware express.static to serve static files, such as images, CSS, JavaScript, etc.
You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this −

app.use(express.static('public'));

upload file

var bodyParser = require('body-parser');
var multer  = require('multer');
let storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null,config.filesUploadPath);
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname);
    },
});

let uploadFile = multer({
    storage: storage,
    limits: { fileSize: config.fileMaxSize }
}).single(config.fileQueryName);

const UploadFile = [uploadFile,async (req, res) => {
    try {
        let file=req[config.fileQueryName];
        fs.renameSync(file.destination+file.originalname,newName);
    } catch (err) {
    }
}];

cookies management

var express      = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

app.get('/', function(req, res) {
   console.log("Cookies: ", req.cookies)
})
app.listen(8081)

middleware

app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...')
  next()
}, function (req, res) {
  res.send('Hello from B!')
})
var cb0 = function (req, res, next) {
  console.log('CB0')
  next()
}

var cb1 = function (req, res, next) {
  console.log('CB1')
  next()
}

var cb2 = function (req, res) {
  res.send('Hello from C!')
}

app.get('/example/c', [cb0, cb1, cb2])//multiple response
let config=require("./config");
let express=require("express");

let app=express();
app.use(function(req,res,next){
    console.log("middleware");
    next();
});
app.get('/name',function (req,res){
    res.send(req.query);
});
let server=app.listen(config.port,()=>{
    console.log(server);
});
var express = require('express')
var router = express.Router()

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  console.log('Time: ', Date.now())
  next()
})
// define the home page route
router.get('/', function (req, res) {
  res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
  res.send('About birds')
})

module.exports = router

Content-Type: application/json

app.use(express.json())

Content-Type: application/x-www-form-urlencoded

app.use(express.urlencoded({
  extended: true
}))

and you can acess to it by

req.body.fieldName;

raw data

const express=require("express");
const bodyParser = require('body-parser');

let options = {
    inflate: true,
    limit: '100kb',
    type: 'text/plain'
};
let app=express();
app.use(bodyParser.raw(options));

app.post("/hello",(req,res)=>{
    res.send(req.body);//body is string if type: 'text/*' else buffer
})
app.listen(8081,()=>{});

HTTP headers

app.get('/', (req, res) => {
  console.log(req.headers)
})
app.get('/', (req, res) => {
  req.header('User-Agent')
  req.get('User-Agent');
})

Response Methods And Properties

The methods on the response object (res) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.

MethodDescription
res.download()Prompt a file to be downloaded.
res.end()End the response process.
res.json()Send a JSON response.
res.jsonp()Send a JSON response with JSONP support.
res.redirect()Redirect a request.
res.render()Render a view template.
res.send()Send a response of various types.
res.sendFile()Send a file as an octet stream.
res.sendStatus(), res.status(code)Set the response status code and send its string representation as the response body.
res.apphold express app
res.cookie()
res.clearCookie()
res.cookie(name, value [, options])
res.set('Content-Type', 'text/html')
res.type('.html')
// => 'text/html'

res.type('html')
// => 'text/html'

res.type('json')
// => 'application/json'

res.type('application/json')
// => 'application/json'

res.type('png')
// => image/png:

for more visit this link

https://expressjs.com/en/4x/api.html

NODE.JS Introduction

Node.js = Runtime Environment + JavaScript Library

first application

install link

https://github.com/nodesource/distributions/blob/master/README.md
var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('Hello World!');
}).listen(8080);
node myfirst.js

Modules

module.exports.name="mohammed";
module.exports.surName="alabdali";
var job=require("./Job");
console.log(job.name,job.surName);

NPM (Node Package Manager)
Online repositories for node.js packages/modules which are searchable


//update npm 
$ sudo npm install npm -g

//to install npm module
$ npm install <Module Name>
$ npm install express

//to install module in globa
$ npm install express -g

//to install package.json modules
npm instsll 

//to install module and add it to debendencies in package.json
npm install linq -P

//to install module and add it to devDependencies in package.json
npm install nodemon -D

//check all modules installed globally
$ npm ls -g

//uninstall module 
$ npm uninstall express

//update module 
$ npm update express

//search 
$ npm search express
var express = require('express');

package.json scripts

"scripts": {
    "start": "node --inspect=5858 -r ts-node/register ./src/server.ts",
    "start:watch": "nodemon",
    "build": "tsc  && copyfiles -u 1 ./src/**/*.env ./dist",
    "prod": "npm run build && npm run start",
    "dev": "nodemon ./src/server.ts",
    "debug": "nodemon --inspect ./src/server.ts",
    "baslat": "npm run build  && forever start ./dist/server.js"
  }
npm run start or npm start 
npm run prod or npm prod
npm debug or npm run debug

Process Module

The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require()

process.stderr.write("hello world");
process.stdin.on("data", (data) => {
    const name = data.toString().trim().toUpperCase();
    if (name !== "") {
        process.stdout.write(`Hello ${name}!`);
    } else {
        process.stderr.write("Input was empty.");
    }
});
process.on('exit', function () {
  fs.writeFileSync('/tmp/myfile', 'This MUST be saved on exit.');
});
process.on('uncaughtException', function (err) {
  console.error('An uncaught error occurred!');
  console.error(err.stack);
});

The default behavior on uncaughtException is to print a stack trace and exit – using the above, your program will display the message provided and the stack trace, but will not exit.

There are also a variety of methods attached to the process object, many of which deal with quite advanced aspects of a program. We’ll take a look at a few of the more commonly useful ones, while leaving the more advanced parts for another article.

process.exit exits the process. If you call an asynchronous function and then call process.exit() immediately afterwards, you will be in a race condition – the asynchronous call may or may not complete before the process is exited. process.exit accepts one optional argument – an integer exit code. 0, by convention, is an exit with no errors.

process.cwd returns the ‘current working directory’ of the process – this is often the directory from which the command to start the process was issued.

process.chdir is used to change the current working directory. For example:

setTimeout(function () {
  // code here
}, 0)

process.nextTick(function () {//prefer this
  console.log('Next trip around the event loop, wheeee!')
});

The process.argv property returns an array containing the command-line arguments passed when the Node.js process was launched.

The child_proccess Module

shell.exec("ping malabdali.com",(error, stdout, stderr)=>{
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});
const { spawn } = require("child_process");

const ls = spawn("ls", ["-la"]);

ls.stdout.on("data", data => {
    console.log(`stdout: ${data}`);
});

ls.stderr.on("data", data => {
    console.log(`stderr: ${data}`);
});

ls.on('error', (error) => {
    console.log(`error: ${error.message}`);
});

ls.on("close", code => {
    console.log(`child process exited with code ${code}`);
});

fs and path Modules

Path

path.basename('/foo/bar/baz/asdf/quux.html');
// Returns: 'quux.html'

path.basename('/foo/bar/baz/asdf/quux.html', '.html');
// Returns: 'quux'

path.dirname('/foo/bar/baz/asdf/quux');
// Returns: '/foo/bar/baz/asdf'

path.extname('index.html');
// Returns: '.html'

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'

fs sync

const fs = require("fs");
const path = require("path");
const filepath = path.join(process.cwd(), "hello.txt");
const contents = fs.readFileSync(filepath, "utf8");
console.log("File Contents:", contents);
const upperContents = contents.toUpperCase();
fs.writeFileSync(filepath, upperContents);
console.log("File updated.");

fs async

const fs = require("fs");
const path = require("path");
const filepath = path.join(process.cwd(), "hello.txt");
fs.readFile(filepath, "utf8", (err, contents) => {
  if (err) {
    return console.log(err);
  }
  console.log("File Contents:", contents);
  const upperContents = contents.toUpperCase();
  updateFile(filepath, upperContents);
});
function updateFile(filepath, contents) {
  fs.writeFile(filepath, contents, (err) => {
    if (err) throw err;
    console.log("File updated.");
  });
}

fs promises

const fs = require("fs").promises;
const path = require("path");
const filepath = path.join(process.cwd(), "hello.txt");
async function run() {
  try {
    const contents = await fs.readFile(filepath, "utf8");
    console.log("File Contents:", contents);
  } catch (error) {
    console.error(error);
  }
}
run();
function printMetadata(file) {
  try {
    const fileStats = fs.statSync(file);
    console.log(fileStats);
  } catch (err) {
    console.error("Error reading file path:", file);
  }
}

Watching for file updates
Node.js’s fs module provides functionality that enables you to watch files and track when files or directories are created, updated, or deleted.
In this recipe, we’ll create a small program named watch.js that watches for changes in a file using the watchFile() API and then prints a message when a change has occurred.

const fs = require("fs");
const file = "./file.txt";
const moment = require("moment");
fs.watch(file, (eventType, filename) => {
    const time = moment().format("MMMM Do YYYY, h:mm:ss a");
    return console.log(`${filename} updated ${time}`);
});

Events

var events = require('events');

let emitter=new events.EventEmitter();
emitter.on("click",()=>{console.log("call 1")});
emitter.on("click",()=>{console.log("call 2")});
emitter.on("click",()=>{console.log("call 3")});
emitter.emit("click");//call 1 call 2 call 3
var events = require('events');

function fun1(){
    console.log("fun1");
}
function fun2(){
    console.log("fun2");
}

let emitter=new events.EventEmitter();
emitter.addListener("click",fun1);
emitter.addListener("click",fun2);
emitter.emit("click");//fun1,fun2
emitter.removeListener("click",fun1);
emitter.emit("click");//fun2

buffer

Pure JavaScript is Unicode friendly, but it is not so for binary data. While dealing with TCP streams or the file system, it’s necessary to handle octet streams. Node provides Buffer class which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.Buffer class is a global class that can be accessed in an application without importing the buffer module.

var buf = new Buffer(10);
var buf = new Buffer([10, 20, 30, 40, 50]);
var buf = new Buffer("Simply Easy Learning", "utf-8");
buf = new Buffer(256);
len = buf.write("Simply Easy Learning");

console.log("Octets written : "+  len);//20
buf.toString([encoding][, start][, end]) 
Live Demo
buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
  buf[i] = i + 97;
}

console.log( buf.toString('ascii'));       // outputs: abcdefghijklmnopqrstuvwxyz
console.log( buf.toString('ascii',0,5));   // outputs: abcde
console.log( buf.toString('utf8',0,5));    // outputs: abcde
console.log( buf.toString(undefined,0,5)); // encoding defaults to 'utf8', outputs abcde
var buffer1 = new Buffer('TutorialsPoint ');
var buffer2 = new Buffer('Simply Easy Learning');
var buffer3 = Buffer.concat([buffer1,buffer2]);

console.log("buffer3 content: " + buffer3.toString());
var buffer1 = new Buffer('ABC');

//copy a buffer
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());
Live Demo
var buffer1 = new Buffer('TutorialsPoint');

//slicing a buffer
var buffer2 = buffer1.slice(0,9);
console.log("buffer2 content: " + buffer2.toString());

Streams

var fs = require("fs");
var data = '';

// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Set the encoding to be utf8. 
readerStream.setEncoding('UTF8');

// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
   data += chunk;
});

readerStream.on('end',function() {
   console.log(data);
});

readerStream.on('error', function(err) {
   console.log(err.stack);
});

console.log("Program Ended");//call first
var fs = require("fs");
var data = 'Simply Easy Learning';

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');

// Mark the end of file
writerStream.end();

// Handle stream events --> finish, and error
writerStream.on('finish', function() {
   console.log("Write completed.");
});

writerStream.on('error', function(err) {
   console.log(err.stack);
});

console.log("Program Ended");
var fs = require("fs");

// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Pipe the read and write operations
// read input.txt and write data to output.txt
readerStream.pipe(writerStream);

console.log("Program Ended");

Ecmascript 6

Variables

different between let and var

{
    var a=12;
    let b=22;
}
console.log(a);//12
console.log(b);// undefined

const

const x = 10
x = 12 // will result in an error!!

const a={};
a.m=12;
console.log(a);//{ m: 12 }
a={};//error

const arr=[1,2,3];
arr.push(4);//[1,2,3,4]
arr=[];//error

var and hoisting

Variable hoisting allows the use of a variable in a JavaScript program, even before it is declared. Such variables will be initialized to undefined by default. JavaScript runtime will scan for variable declarations and put them to the top of the function or script. Variables declared with var keyword get hoisted to the top.

//hoisted to top ; var i = undefined
for (var i = 1;i <= 5;i++){
   console.log(i);
}
console.log("after the loop i value is "+i);
//variable company is hoisted to top , var company = undefined
console.log(company); // using variable before declaring
var company = "TutorialsPoint"; // declare and initialized here
console.log(company);
   var balance = 5000
   console.log(typeof balance)//Number
   var balance = {message:"hello"}
   console.log(typeof balance)//Object

Operators

let a=null;
let b=a||12;//right hand if left hand is false b=12

let a=null;
let b=a&&12;//right hand if left hand is not false

?. and Nullish (??) operator

let m=undefined;
console.log(m?.hello)//undefined
let m=undefined??"mohammed";//right hand if left is null or undefined
console.log(m);//mohammed

Spread operator

<script>
   function addThreeNumbers(a,b,c){
      return a+b+c;
   }
   const arr = [10,20,30]
   console.log('sum is :',addThreeNumbers(...arr))
   console.log('sum is ',addThreeNumbers(...[1,2,3]))
</script>
   //copy array using spread operator
   let source_arr = [10,20,30]
   let dest_arr = [...source_arr]
   console.log(dest_arr)
	
   //concatenate two arrays
   let arr1 = [10,20,30]
   let arr2 =[40,50,60]
   let arr3 = [...arr1,...arr2]
   console.log(arr3)
<script>
   //copy object
   let student1 ={firstName:'Mohtashim',company:'TutorialsPoint'}
   let student2 ={...student1}
   console.log(student2)
   //concatenate objects
   let student3 = {lastName:'Mohammad'}
   let student4 = {...student1,...student3}
   console.log(student4)
</script>

Loops

in loop

let a={a:"hello",b:"world"}
for(let m in a){
    console.log(a[m]);
}

of loop

let a=[1,2,3,4];
for(let m of a){
    console.log(m);
}

label with break

outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
   console.log("Outerloop: " + i);
   innerloop:
   for (var j = 0; j < 5; j++){
      if (j > 3 ) break ; // Quit the innermost loop
      if (i == 2) break innerloop; // Do the same thing
      if (i == 4) break outerloop; // Quit the outer loop
      console.log("Innerloop: " + j);
   }
}

Functions

constructor function

function A(val){
    this.b=val;
}

let a=new A(12);
console.log(a.b);//12
console.log(a instanceof A);//true
console.log(A.prototype===a.__proto__);//true
A.prototype.x=32;
console.log(a.x);//32
console.log(a.hasOwnProperty("x"));//false
a.x=321;
console.log(a.hasOwnProperty("x"));//true
function B(){

}

function A(val){
    this.val=val;
}
A.prototype=new B();
A.prototype.val2=44;

let m=new A(12);
console.log(m instanceof A,m instanceof B);//true true
console.log(m.constructor);//B

Rest parameters

function fun1(...params) { 
   console.log(params.length); 
}  
fun1();  
fun1(5); 
fun1(5, 6, 7); 

Lambda functions

var msg = ()=> { 
   console.log("function invoked") 
} 
msg() 

var msg = x=> { 
   console.log(x) 
} 
msg(10)

Function Hoisting

Like variables, functions can also be hoisted. Unlike variables, function declarations when hoisted, hoists the function definition rather than just hoisting the function’s name.

hoist_function();  //call function
function hoist_function() { 
   console.log("foo"); 
} 
hoist_function(); // TypeError: hoist_function() is not a function  
var hoist_function() = function() { 
   console.log("bar"); 
};

Generator function

"use strict" 
function* rainbow() { 
   // the asterisk marks this as a generator 
   yield 'red'; 
   yield 'orange'; 
   yield 'yellow'; 
   yield 'green'; 
   yield 'blue'; 
   yield 'indigo'; 
   yield 'violet'; 
} 
for(let color of rainbow()) { 
   console.log(color); 
} 
function* ask() { 
   const name = yield "What is your name?"; 
   const sport = yield "What is your favorite sport?"; 
   return `${name}'s favorite sport is ${sport}`; 
}  
const it = ask(); 
console.log(it.next()); 
console.log(it.next('Ethan'));  
console.log(it.next('Cricket')); 

destructing parameters

fun1({A:"hello",B:"world"});
fun2(["hello","world"]);
function fun1({A,B}){
    console.log(A,B);
}
function fun2([A,B]){
    console.log(A,B);
}

bind and apply

function  f(){
    console.log(this.v);
    console.log(arguments);
}
let ob={v:12};
f.bind(ob)();//12
f.apply(ob,["a","b","c"]);//12   [Arguments] { '0': 'a', '1': 'b', '2': 'c' }

Objects

let A={};
let B=A;
let C={};
C[A]=12;
console.log(C[B]);
let k=12;
let A={k};
console.log(A["k"]);
var myCar = new Object(); 
myCar.make = "Ford"; //define an object 
myCar.model = "Mustang"; 
myCar.year = 1987;  

console.log(myCar["make"]) //access the object property 
console.log(myCar["model"]) 
console.log(myCar["year"])

let A={"v1":12};
let B=Object.create(A);
console.log(B.v1);//12
console.log(B===A);//false

delete property

// Creates a new object, myobj, with two properties, a and b. 
var myobj = new Object; 
myobj.a = 5; 
myobj.b = 12; 

// Removes the ‘a’ property 
delete myobj.a; 
console.log ("a" in myobj) // yields "false"

comparing

var val1 = {name: "Tom"}; 
var val2 = {name: "Tom"}; 
console.log(val1 == val2)  // return false 
console.log(val1 === val2)  // return false

object de-structing

<script>
let student = {
   rollno:20,
   name:'Prijin',
   cgpa:7.2
}

//destructuring to same property name
   let {name,cgpa} = student
   console.log(name)
   console.log(cgpa)

//destructuring to different name
   let {name:student_name,cgpa:student_cgpa}=student
   console.log(student_cgpa)
   console.log("student_name",student_name)
</script>
let customers= {
    c1:101,
    c2:102,
    c3:103
}

let {c1,...others} = customers
console.log(c1)//c1
console.log(others)//c2,c3

let emp = {
    id:101,
    address:{
        city:'Mumbai',
        pin:1234
    }
}
let {address} = emp;

console.log(address)
let {address:{city,pin}} = emp
console.log(city)//mumbai

define property

let B={a:1,b:2,c:3};
Object.defineProperty(B,"h",{ enumerable:true, value:4, configurable:true,writable:true});
for(let m in B){
    console.log(m);//a,b,c,h all of them they are enumerable
}
B.h={A:32};//can write on value because it writable
delete  B.h;//can delete because it configurable
console.log(B.h);

set and get

let B={a:1,b:2,c:3};

Object.defineProperty(B,"d",{ set(v) {console.log("hello");
    },get() {console.log("world");
    }});
B.d=345;//hello
let m=B.d;//world

let C={set name(v) {console.log("set ",v);
    },get name() {
    console.log("get");
    }};
C.name=43;//set   43

function constructor(){
    this.val=12;
}
let obj=new constructor();
obj.a=1;
obj.b=2;
console.log(Object.keys(obj));//[val,a,b]

?. and ?? operator

let m=undefined;
console.log(m?.hello)//undefined
let m=undefined??"mohammed";
console.log(m);//mohammed

Number

var num = new Number(10);
console.log(num.toString());
console.log(num.toString(2));//binary
console.log(num.toString(8));//octal

let val=41.2334
console.log(val.toFixed(1))//41.2
console.log(Number(" 12.453  "));//12.453

let val=Number("hello");
console.log(Number.isNaN(val));//true

let val=new Number(12);//instanceof Number
let val=12;//not instanceof Number

String

const str = "Please locate where 'locate' occurs!";
console.log(str.length);//36
console.log(str.indexOf("locate"));//7
console.log(str.toUpperCase());//PLEASE LOCATE WHERE 'LOCATE' OCCURS!
console.log(str.split(' '));//[ 'Please', 'locate', 'where', "'locate'", 'occurs!' ]
console.log(str.endsWith('!'));//true
console.log(str.substr(7))//locate where 'locate' occurs!

let str2="  I  Like  Frutes  ";
str2=str2.trim();
console.log(str2.replace(/(\s+)/i,','));//I,Like  Frutes
console.log(str2.search(/\w{0,2}\s/i));//0
console.log(str2.match(/(\w+\s*)/gi));//[ 'I  ', 'Like  ', 'Frutes' ]

var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);//Hello World

Array

let arr = ["orange", "mango", "banana", "sugar", "tea"];
let removed = arr.splice(2, 0, "water");//no remove only add
console.log(arr);//orange,mango,water,banana,sugar,tea

removed = arr.splice(3, 1);
console.log("After adding 1: " + arr );//orange,mango,water,sugar,tea
console.log("removed is: " + removed);//banana

var arr = ["orange", "mango", "banana", "sugar", "tea"]; 
console.log("arr.slice( 1, 2) : " + arr.slice( 1, 2) );//mango
console.log("arr.slice( 1, 3) : " + arr.slice( 1, 3) );//mango,banana
var arr = new Array("First","Second","Third"); 
var str = arr.join();console.log("str : " + str );  
var str = arr.join(", "); 
console.log("str : " + str );  

var str = arr.join(" + "); 
console.log("str : " + str );

/*
str : First,Second,Third 
str : First, Second, Third 
str : First + Second + Third 
*/
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
array.sort( compareFunction ); //or with no compare functions for numbers ands string array
push(element)//add to end 
unshift(element)//add to first
shift()//remove first
pop()//remove last 
function isBigEnough(element, index, array) { 
   return (element >= 10); 
} 
var retval = [2, 5, 8, 1, 4].some(isBigEnough); 
console.log("Returned value is : " + retval ); //false

var retval = [12, 5, 8, 1, 4].some(isBigEnough); 
console.log("Returned value is : " + retval );//true

var passed = [12, 5, 8, 130, 44].filter(isBigEnough); 
console.log("Test Value : " + passed );  //12,130,44

const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);//Array [2, 8, 18, 32]

const array1 = [1, 2, 3, 4];
const reducer = (previousValue, currentValue) => previousValue + currentValue;
console.log(array1.reduce(reducer));// 1 + 2 + 3 + 4=10
console.log(array1.reduce(reducer, 5));// 5 + 1 + 2 + 3 + 4 =15

Map

let daysMap = new Map();
daysMap.set('1', 'Monday');
daysMap.set('2', 'Tuesday');
daysMap.set('3', 'Wednesday');
console.log(daysMap.size);

let andy = {ename:"Andrel"},
    varun = {ename:"Varun"},
    prijin = {ename:"Prijin"}
let empJobs = new Map([[andy,'Software Architect'],[varun,'Developer']]);
console.log(empJobs)//{{…} => "Software Architect", {…} => "Developer"}
'use strict' 
var roles = new Map([ 
   ['r1', 'User'], 
   ['r2', 'Guest'], 
   ['r3', 'Admin'], 
]);
for(let r of roles.entries()) 
console.log(`${r[0]}: ${r[1]}`);

let m=new Map([["ali",1],["mohammed",2]]);
for(let [k,v] of m.entries()){
    console.log(k,v);
}

Promise

   function add_positivenos_async(n1, n2) {
      let p = new Promise(function (resolve, reject) {
         if (n1 >= 0 && n2 >= 0) {
            //do some complex time consuming work
            resolve(n1 + n2)
         }
         else
            reject('NOT_Postive_Number_Passed') 
         })
         return p;
   }

   add_positivenos_async(10, 20)
      .then(successHandler) // if promise resolved
      .catch(errorHandler);// if promise rejected

   add_positivenos_async(-10, -20)
      .then(successHandler) // if promise resolved
      .catch(errorHandler);// if promise rejected

   function errorHandler(err) {
      console.log('Handling error', err)
   }
   function successHandler(result) {
      console.log('Handling success', result)
   }

   console.log('end')
function add_positivenos_async(n1, n2) {
    let p = new Promise(function (resolve, reject) {
        if (n1 >= 0 && n2 >= 0) {
            //do some complex time consuming work
            resolve(n1 + n2)
        }
        else
            reject('NOT_Postive_Number_Passed')
    })
    return p;
}

add_positivenos_async(10,20)
    .then(function(result){
        console.log("first result",result)
        return add_positivenos_async(result,result)
    }).then(function(result){
    console.log("second result",result)
    return add_positivenos_async(result,result)
}).then(function(result){
    console.log("third result",result)
})

console.log('end')

promise.all()
This method can be useful for aggregating the results of multiple promises.

   function add_positivenos_async(n1, n2) {
      let p = new Promise(function (resolve, reject) {
         if (n1 >= 0 && n2 >= 0) {
            //do some complex time consuming work
            resolve(n1 + n2)
         }
         else
            reject('NOT_Postive_Number_Passed')
      })

      return p;
   }
   //Promise.all(iterable)

Promise.all([add_positivenos_async(10,20),add_positivenos_async(30,40),add_positivenos_async(50,60)])
   .then(function(resolveValue){
      console.log(resolveValue[0])
      console.log(resolveValue[1])
      console.log(resolveValue[2])
      console.log('all add operations done')
   })
   .catch(function(err){
      console.log('Error',err)
   })
   console.log('end')

/*
end
30
70
110
all add operations done
*/

promise.race() This function takes an array of promises and returns the first promise that is settled.

   function add_positivenos_async(n1, n2) {
      let p = new Promise(function (resolve, reject) {
         if (n1 >= 0 && n2 >= 0) {
            //do some complex time consuming work
            resolve(n1 + n2)
         } else
            reject('NOT_Postive_Number_Passed')
      })

      return p;
   }

   //Promise.race(iterable)
   Promise.race([add_positivenos_async(10,20),add_positivenos_async(30,40)])
   .then(function(resolveValue){
      console.log('one of them is done')
      console.log(resolveValue)
   }).catch(function(err){
      console.log("Error",err)
   })

   console.log('end')

async

async function  fun(){
    return 100;
}

Promise.all([fun(),fun(),fun()]).then((res)=>{
    console.log(res);});

await


async function  fun(){
    return 100;
}

async  function  fun2(){
    let prom=Promise.all([fun(),fun(),fun()]);
    let res=await prom;
    return res;
}

fun2().then(res=>{console.log(res)});//[ 100, 100, 100 ]
async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait until the promise resolves (*)

  alert(result); // "done!"
}

f();

class

class A{
    m=12;
    constructor(val) {
        console.log(val);
        this.m=val;
    }
    set value(val){
        this.m=val;
    }

    get value() {
        return this.m;
    }
}

let a=new A(12);//12
a.value=22;
console.log(a.value);//22
class A{
    m=12;
    constructor(val) {
        console.log("A : ",val);
        this.m=val;
    }
    set value(val){
        this.m=val;
    }

    get value() {
        return this.m;
    }
}
class B extends A{
    constructor(val) {
        super(val);
        console.log("B : ",val)
    }
}
let b=new B(12);//A : 12 B : 12
class A{
    #m=12;//private field
}

get constructor from object

class A{
}

let a=new A();
console.log(a.constructor==A);//true

call super members

class A{
    constructor() {
    }
    fun(){
        console.log("A");
    }
}

class B extends A{
    constructor() {
        super();
    }
    fun(){
        super.fun();
        console.log("B");
    }

}

let b=new B();
b.fun();//A B

export and import

// export an array
export let months = ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

// export a constant
export const MODULES_BECAME_STANDARD_YEAR = 2015;

// export a class
export class User {
  constructor(name) {
    this.name = name;
  }
}

export function sayHi(user) {
  alert(`Hello, ${user}!`);
}  // no ; at the end

// ? say.js
function sayHi(user) {
  alert(`Hello, ${user}!`);
}
function sayBye(user) {
  alert(`Bye, ${user}!`);
}
export {sayHi, sayBye}; // a list of exported variables

// ? main.js
import {sayHi, sayBye} from './say.js';
sayHi('John'); // Hello, John!
sayBye('John'); // Bye, John!

// ? main.js
import * as say from './say.js';
say.sayHi('John');
say.sayBye('John');
// ? main.js
import {sayHi as hi, sayBye as bye} from './say.js';

hi('John'); // Hello, John!
bye('John'); // Bye, John!
// ? say.js
...
export {sayHi as hi, sayBye as bye};

// ? main.js
import * as say from './say.js';

say.hi('John'); // Hello, John!
say.bye('John'); // Bye, John!

Export default

In practice, there are mainly two kinds of modules.

  1. Modules that contain a library, pack of functions, like say.js above.
  2. Modules that declare a single entity, e.g. a module user.js exports only class User.

Mostly, the second approach is preferred, so that every “thing” resides in its own module.

// ? user.js
export default class User { // just add "default"
  constructor(name) {
    this.name = name;
  }
}

// ? main.js
import User from './user.js'; // not {User}, just User
new User('John');
function sayHi(user) {
  alert(`Hello, ${user}!`);
}

// same as if we added "export default" before the function
export {sayHi as default};

// ? user.js
export default class User {
  constructor(name) {
    this.name = name;
  }
}

export function sayHi(user) {
  alert(`Hello, ${user}!`);
}

// ? main.js
import {default as User, sayHi} from './user.js';

new User('John');

// ? main.js
import * as user from './user.js';

let User = user.default; // the default export
new User('John');

re-export

export {sayHi} from './say.js'; // re-export sayHi
export {default as User} from './user.js'; // re-export default
export * from './user.js'; // to re-export named exports
export {default} from './user.js'; // to re-export the default export

operators

Operator_NameDescriptionExample
inIt is used to check for the existence of a property on an object.let Bike = {make: ‘Honda’, model: ‘CLIQ’, year: 2018}; console.log(‘make’ in Bike); // Output: true
deleteIt is used to delete the properties from the objects.let Bike = { Company1: ‘Honda’, Company2: ‘Hero’, Company3: ‘Royal Enfield’ }; delete Bike.Company1; console.log(Bike); // Output: { Company2: ‘Hero’, Company3: ‘Royal Enfield’ }
typeofIt returns the data type of the operand.let message = “Welcome to ” + “JavaTpoint”; console.log(typeof message); // Output: String
instanceofIt is used to check if the object is of a specified type or not.let arr = [1, 2, 3]; console.log( arr instanceof Array ); // true console.log( arr instanceof String ); // false

Typescript

class A{
}
let m:A;
//============================
type AA={
    m:string
}
let mm:AA={m:"hello"};
//=================================
function fun(l:number,s:boolean):void{//can return null or undefined or nothing
    return undefined;
}

function fun2(cb,a?:string){ //second parameter can be empty
}
fun2(()=>{});
//===============================
let strArr:string[];//accept only array of string
let strArr2:[string,number];//accept only array of strings and numbers
let strArr3:Array<string>;
//========================
let any:any;//take any value

to build js from ts file you can

npm install typescript -D -g
npm link typescript
tsc file.ts