2021年9月3日 星期五

[typescript, main] The Javascript/TypeScript FAQ

 The Javascript/TypeScript FAQ

井民全, Jing, mqing@gmail.com


The Public FAQ Index (view)


Table of contents

1. TypeScript 2

1.1. Debug 4

1.2. Import 5

1.3. Operator 6

1.4. Cast 6

1.5. Variable 6

1.6. Binary data buffer 7

1.6.1. ArrayBuffer 7

1.6.2. TypedArray 8

1.6.3. Buffer (This is a Node class) 9

1.7. Array 9

1.8. Character 11

1.9. String 12

1.10. Loop 12

1.11. Function 12

1.12. Class 14

1.13. Object Type 15

1.14. Mapped Type 20

1.15. File 21

1.16. Log 22

1.17. Newtork 23

1.18. Signal 23

2. JavaScript 24

2.1. Debug 25

2.2. Variable 25

2.3. Class 26

2.4. Module 28

2.5. Function 28

2.6. I/O 29

2.7. Async 31

2.8. Loop 31

2.9. Array 32

2.10. Object inspect 33



[ecma, sheet] The ECMAScript sheet (view)

1. TypeScript 

  1. [typescripobject, doc, official] typedoc (ref)

  1. [typescript, doc, handbook] The typescript handbook (ref)

  2. [typescript, tool, play] Online playground (ref)

  3. [typescript, tool, node] ts-node (ref)

  4. [typescript, install] How to install typescript


# install npm

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.5/install.sh | bash

export NVM_DIR="$HOME/.nvm"


[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"


nvm install v8.6.0


# install typescript

npm install -g typescript

npm install -g tslint



# install typescript

npm install -g typescript

npm install -g tslint


  1. [typescript, init,  tsconfig] How to build tconfig.json (ref)


tsc --init


  1. [typescript, init, tsconfig] An example of the tsconfig.json (ref)


{

  "compilerOptions": {

    "target": "ES5",

    "module": "system",

    "moduleResolution": "node",

    "sourceMap": true,

    "emitDecoratorMetadata": true,

    "experimentalDecorators": true,

    "removeComments": false,

    "noImplicitAny": false

  },

  "exclude": [

    "node_modules",

    ".npm"

  ]

}

  1.  

  1. [typescript, package.json, template] Template package.json for typescript build


// file: package.json

{

...

  "scripts": {

    "start": "npm-run-all build run:app",

    "run:app": "node ./src/index.js",       // source code lives here

    "build": "tsc",

    "watch:build": "tsc --watch",

    "clean": "rm -fr ./out; rm -fr node_modules; find . -name \"*.js\" -type f|xargs rm -f; find . -name \"*.map\" -type f|xargs rm -f",

    "test": "echo \"Error: no test specified\" && exit 1"

  },

 ...

}


// Usage

npm start


  1. [typescript, decorators] decoratorts (ref)

  2. [typescript, clean] How to clean the unnecessary files, makeclean (view) (ref)

    1. Bash bash
      . ./make-clean.sh

#!/bin/bash

find . -name "*.js" -type f|xargs rm -f

find . -name "*.map" -type f|xargs rm -f

find . -name "node_modules" -type d -prune -exec rm -rf '{}' +

  1. package.json version
    npm run clean

File: package.json

"scripts": {

    "build" : "tsc",

    "clean" : "rm -fr dist; rm -fr node_modules; find . -name \"*.js\" -type f|xargs rm -f; find . -name \"*.map\" -type f|xargs rm -f; find . -name \"*.raw\" -type f|xargs rm -f; find . -name \"*.log\" -type f|xargs rm -f"

  }


  1. [typescript, config] How to implement config (view)


1.1. Debug

  1. [typescript, vscode] How to setup a standard launch.json for typescript (view)


// launch.json

"program": "${workspaceFolder}/index.ts",

"preLaunchTask": "tsc: build - tsconfig.json",


  1. [typescript, vscode] How to debug typescript app with vscode (view) (ref)


Step 1: Enable sourceMap


//File: tsconfig.json


...

"sourceMap": true,

...


Step 2: Setup the debug configuration


//File: launch.json


...

"program": "${workspaceFolder}/index.ts",

"preLaunchTask": "tsc: build - tsconfig.json",

...



1.2. Import

  1. [typescript, import] A collection of import packages


import {JSDOM} from 'jsdom';

import cheerio from 'cheerio';


import fs = require('fs');

import https = require('https');

  1. [typescript, import] How to import a function (ref)


// in util.ts

export function myfunction(){

    console.log("hello");

}



Usage

import {myfunction} from './util'



1.3. Operator

  1. [operator] All operators (ref)

  2. [op, !] How to use the typescript Non-null assertion (ref)


// It tells TypeScript that even though something looks like it could be null, it can trust you that it's not:


let name1:string = person.name!; 

                          //                            ^ note the exclamation mark here


  1. [op, ?] Optional parameters and properties (ref)


type T1 = (x?: number) => string; // x has type number | undefined

type T2 = (x?: number | undefined) => string; // x has type number | undefined


1.4. Cast

  1. [typescript, variable, cast] How to do the typecast


Key

let var1:type1 | type2 | type3;

let var2: type1 = var1 as type1


Example

import net, {Server, AddressInfo} from 'net'
const address:AddressInfo = server.address() as AddressInfo;

        console.log('Server ready. (for accept audio stream). port = ' + address.port);



1.5. Variable

  1. [typescript, variable] What is the maybe type (view)


bar: ?string    // case 1: accepts a string, null or void:

bar?: string       // case 2: Accepts only a string or void:


  1. [typescript, variable, undefined] How to determine a variable whether undefined


if (typeof strData === 'undefined'){

   return;

}

  1. [typescript, variable] What is the ComputedPropertyName (mdn)(1380)

    1. Why we need to put e.target.name in square brackets []? [duplicate]

  2. [typescript, global] How to use global variable (view)



1.6. Binary data buffer

1.6.1. ArrayBuffer

  1. [typescript, ArrayBuffer] The definition of ArrayBuffer (ref)

    1. a generic, fixed-length raw binary data buffer

  2. [typescript, ArrayBuffer, typedArray2ArrayBuffer] How to convert typed array to ArrayBuffer (ref)


int16Array.buffer

  1. [typescript, ArrayBuffer, ArrayBuffer2int16Array] How to convert ArrayBuffer to typed array (ref)


let byteArray:ArrayBuffer = new ArrayBuffer(10);

...

let viewArray:Int16Array = new Int16Array(byteArray);

  1. [typescript, ArrayBuffer, ArrayBuffer2Buffer] How to conver ArrayBuffer variable to Buffer class instance (ref)


Buffer.from(arrayBufferData);


1.6.2. TypedArray

  1. [typescript, typedarray] The definition of TypedArray (ref)

    1. an array-like view of an underlying binary data buffer.

  2. [typescript, typedArray2Buffer] How to conver a typed array to Buffer


int16Array2Buffer(int16Array:Int16Array):ArrayBuffer {

        return Buffer.from(int16Array.buffer);

    }


  1. [typescript, typedArray2numberArray] How to conver a typed array to number array


Code

let int16ArrayData:Int16Array = new Int16Array([1, 2, 3]);

console.log('int16ArrayData = ', int16ArrayData);


let numArrayData:Array<number> = Array.from(int16ArrayData);

console.log('numArrayData = ', numArrayData);


Result

"int16ArrayData = ", [object Int16Array]

"numArrayData = ", [1, 2, 3]


  1. [uint8Array, int] Conver a 4 bytes of uInt8Array to 32-bit integer


function uInt8Array2integer(bufDataChunk:Buffer):number {

        return ((bufDataChunk[0] << 0) + (bufDataChunk[1] << 8) + (bufDataChunk[2] << 16) + (bufDataChunk[3] << 24));

    }





1.6.3. Buffer (This is a Node class)

  1. Buffer objects are used to represent a fixed-length sequence of bytes. (See Nodejs Buffer section.)


1.7. Array

  1. [typescript, array, create] How to create an array-like object (ref)


var myFish = {0:'angel', 1:'clown', 2:'mandarin', 3:'sturgeon', length: 4};

var popped = Array.prototype.pop.call(myFish); //same syntax for using apply( )

console.log(myFish); // {0:'angel', 1:'clown', 2:'mandarin', length: 3} 

console.log(popped); // 'sturgeon'


  1. [typescript, array, init] How to create an array initilized with zero values


let numArray:Array<number> = new Array<number>(100).fill(0);


  1. [typescript, array, spread] What is [...obj] means? (ref)

    1. You can use spread operator to create a new array from existing arrays


let a = [1, 2, 3];

let b = [3, 4, 5];

let copyA = [...a];   // 1, 2, 3

let mergeAB = [...a, ...b]; // 1, 2, 3, 3, 4, 5

let appendA = [...a, 44, 55]; // 1, 2, 3, 44, 55


  1. [typescript, array, foreach] How to enumerate the elements in array


Key:

let arrayData:Array<string> = [];

data.forEach( (data:string) => {

});


Ex:

let strHtml:string="";

  data.forEach((chunk:any) => {

// console.log('chunk = ', chunk.toString());

strHtml = strHtml + chunk.toString();

  });

  1. [typescript, array, add, append] How to append values of an array to the other array without creating a new array. (ref)


Key

push


Code (view)

let arrNumA:Array<number> = [1, 2, 3];

let arrNumB:Array<number> = [5, 6, 7];


arrNumA.push(...arrNumB);

console.log('arrNumA = ', arrNumA);


Result

"arrNumA = ", [1, 2, 3, 5, 6, 7]


Key

splice


Code (view)

let arrNumA:Array<number> = [1, 2, 3];

let arrNumB:Array<number> = [5, 6, 7];


arrNumA.splice(arrNumA.length, 0, ...arrNumB);

console.log('arrNumA = ', arrNumA);


Result

"arrNumA = ", [1, 2, 3, 5, 6, 7]


  1. [typescript, array, add, insert first] How to add values of an array to the beginning of an array without creating a new array (ref)


Key

unshift


  1. [typescript, arra, delete first] How to remove values of the array in place


buffer.splice(0, newDataChunk.length); // 滑動 (從開頭剪掉資料)


  1. [typescript, array, queue] 

    1. 把 陣列 B 的所有東西, append 到原來陣列, 再搭配 splice(0, frameSize) 剪掉/取出前面的資料, 就可以很簡單的製作出一個 cache 水池, 協調進出流量不同速度的問題. 要做這件事, 陣列 B 的成員數量通常很多, append 新資料自然不該使用 concate 來完成, 而應該使用 inplace 版本的 push 或 splice


// Version 1 

const buffer = this.cache.slice(0, 960) // 取資料

 this.cache = this.cache.slice(960) // 滑動


// Version 2

buffer = buffer.concat(newDataChunk); // 放資料在最右邊, [screen + new data]

buffer = buffer.slice(newDataChunk.length); // 滑動, [ old ] + [screen]


// Version 3: 高效率

buffer.splice(0, newDataChunk.length); // 滑動 (從開頭剪掉資料

buffer.push(...newDataChunk); // 放資料在最右邊



  1. .

1.8. Character

  1. [char, ascii] How to conver a character to ascii (ref)


let buff:Buffer = 'xxxxx'

buff[0] == 'i'.charCodeAt(0)


1.9. String

  1. [string, \n] How to remove new line in string


strElement = strElement.replace(/\r?\n|\r/g, " "); // replace \n

  1. [string, include] How to determine a substring wether in a string? (ref)


if (localName.includes('DeviceJing')){

            console.log('found target')

        }


  1. [string, endsWith] How to check the string ends with the characters (ref)


if (strFullFilename.endsWith('.raw')){

      offset = 0;

    }




1.10. Loop

  1. [for in and for of) (view)

1.11. Function

  1. [typescript, callback] How to declare a callback function (ref)


interface Mytype {  (msg: string): void; }


function sayHi(cb: Mytype) {

  cb('Hi!')

}

  1. [typescript, function, return] How to return an array


function myFun():Array<any> {

    ...

    return [data1, data2];

}


// Usage

[data1, data2] = myFun();

  1. [typescript, function, return] How to return a custmized type


function myFun():{myString:string, myNum:number} {

    ...

    return {myString: strData1, myNum: numData2}

}


// Usage v1

let cfg:{myString:string, myNum:number}  = myFun();

console.log('cfg.myString = ', cfg.myString);

console.log('cfg.myNum = ', cfg.myNum);


// Usage v2

let cfg:{myString:string, myNum:number};

cfg =  myFun();

console.log('cfg.myString = ', cfg.myString);

console.log('cfg.myNum = ', cfg.myNum);

  1. [typescript, function, static var] How to declare static variable in function (ref)

  2. [typescript, function, param] What is the Rest parameters (ref)


# allows a function to accept an indefinite number of arguments as an array,

function sum(...theArgs) {

  return theArgs.reduce((previous, current) => {

    return previous + current;

  });

}


console.log(sum(1, 2, 3));

// expected output: 6


console.log(sum(1, 2, 3, 4));

// expected output: 10


  1. [typescript, function, param] The arguments object (ref)


# You can use it to reference the arguments

function func1(a, b, c) {

  console.log(arguments[0]);

  // expected output: 1


  console.log(arguments[1]);

  // expected output: 2


  console.log(arguments[2]);

  // expected output: 3

}


func1(1, 2, 3);




1.12. Class

  1. [typescript, class, constructor] How to create and assign a class instance property from a constructor parameter (ref)

    1. short-cut

class MyClass{

    constructor(public myPublicVar:MyType, normalArg){

    }


    myMethod(){

           this.myPublicVar = ...;

           this.normalArg = ...;   // Error: there is no normalArg property 

    }

}

  1. Traditional way

class MyClass{

    public myPublicVar:MyType = new MyType();

    constructor(normalArg){

          this.normalArg = ...;   // Error: there is no normalArg property

    }


    myMethod(){

           this.myPublicVar = ...;

    }

}


  1. [typescript, class, member] How to declare a constant member in class (ref)


export class MyClass {

    readonly data:number = 123;

}


  1. [typescript, class, method, static] How to declare a static method in Typescript


export class MyClass {

    static method(){

    }

}

  1. [typescript, class, virtual function] How to define a virtual in class (ref)


class Base {

    protected __genData():Float32Array{

        throw new Error('This method is abstract');

    }

}


1.13. Object Type

  1. [typescript, typealias] What is the type alias? (ref)


Aliasing doesn’t actually create a new type - it creates a new name to refer to that type.


# example

type Person = {

 name: string;

 age: number;

};


interface Person {

 name: string;

 age: number;

}



function greet(person: Person) {

  return "Hello " + person.name;

}


  1. [typescript, type alias, function] Alias a function type 


// 重新命名一個新的 type 為 func

// 內容為 一個 function, 傳回字串型態

type func = () => string; 


// 重新命名一個新的 type 為 ThunkAction

// 內容為 一個 有三個參數的 function, 傳回 R type 的東西

type ThunkAction<R> = (dispatch, getState, extraArgument) => R


// This would make R the return type of the `ThunkAction` method. 


Ref: https://bloggie.io/@_ChristineOo/understanding-typings-of-redux-thunk-action




  1. [typescript, object type] How to use the object type (view),  (ref)

    1. Used group and pass around data

# declare

interface Person {

  name: string;

  age: number;

}


# init

let Tom:Person = {name:'Tom', age: 18}


# usage

function greet(person: Person) {

  return "Hello " + person.name;

}


  1. [typescript, object type] What is the object type (view)


let employee: object;


employee = {

    firstName: 'John',

    lastName: 'Doe',

    age: 25,

    jobTitle: 'Web Developer'

};


console.log(employee);



  1. [typescript, object type] How to print object type variable (view)


console.log('/increase. status = ' + JSON.stringify(status));


  1. [typescript, object type] How to use option parameters (ref)

  2. [typescript, object type, para] How to  group and pass around relevant data to constructor (view)


function myFun(buffer:AudioBuffer):{bok:boolean, strMsg:string} {

        if (buffer === null){

            return {bok:false, strMsg:'buffer === null'};

        }

        

        return {bok:true, strMsg: 'ok'};

    }


const {bok, strMsg} = this._uiSoundPlay(this.buffer);

if(!bok){

            console.log(strMsg);

}



class A {

  constructor(options:any) {

    options = {

      op_1: 'op1',

      op_2: 'op2',

      ...options

    };


    const {host, port, op_1, op_2} = options;

    console.log(host);

    console.log(port);

    console.log(op_1);

    console.log(op_2);

  }

}


function main(){

  console.log('start test');

  const options = {host: 'abc', port:123}

  let obj:A = new A(options);

}


main();



  1. [typescript, object type, enumerate] How to enumerate the properties of an object (view), (blog)


interface Status {

    id: number;

    msg: string;

}


let mystatus:Status = {id: 123, msg:'this is the msg'};

for (var prop in mystatus) {

       if (mystatus.hasOwnProperty(prop)) {

           console.log('prop = ' + prop + ', value = ' + mystatus[prop as keyof Status]);

       }

    }

}


  1. [typescript, property] What is the ES6 computed property (ref)


var obj = {};

OR

var car = {type:"Fiat", model:"500", color:"white"};



  1. [typescript, dict, array] How to define a dictionary array 


Code 

let arrayDict:Array<{key:string, value:number}> = [

    {key:'key1', value:0},

    {key:'key2', value:1},

    {key:'key3', value:2},

    {key:'key4', value:3},

  ];


for (let i = 0; i< arrayDict.length; i++){

    console.log('key = ', arrayDict[i].key, ' value = ', arrayDict[i].value);

}


Result

> $ node test.js                                                  [±master ●●●]

key =  key1  value =  0

key =  key2  value =  1

key =  key3  value =  2

key =  key4  value =  3



  1. [typescript, dict, key] How to determined a  key in dictionary


Key:

let hisMap:any = {};

isMap.hasOwnProperty(strData)


Ex:

function getHisbyDate(lstRow:Array<any>){

  let hisMap:any = {};

  lstRow.forEach((row) => {

let strData:string = row[2];

if (typeof strData === 'undefined'){

   return;

}

if(!hisMap.hasOwnProperty(strData)){

       hisMap[strData] = 0;

} else {

       hisMap[strData] = hisMap[strData] + 1;

}

// console.log(strDate);

  });

1.14. Mapped Type

  1. [typescript, mapped, doc] Mapped Types (ref)

  2. [typescript, mapped] How to declare key, value map in typescript


Code

let data:number = 5;

let dictData:{[index:string]:number} = {"a": 1, "b":2};


for (let strKey in dictData){

console.log('strKey = ', strKey);

console.log('vale = ', dictData[strKey]);

}


Object.keys(dictData).forEach(strKey => {

console.log("strKey = " + strKey);

console.log('value = ' + dictData[strKey]);

}

);



Output

strKey =  a

vale =  1

strKey =  b

vale =  2

strKey = a

value = 1

strKey = b

value = 2







1.15. File

  1. [typescript, file, remove] How to remove a file


fs.unlinkSync(strFilename); // remove the file

  1. [typescript, file, append] How to append a file


function toCSV(lstRow:Array<any>, strFilename:string){

  fs.unlinkSync(strFilename); // remove the file

  lstRow.forEach((row) => {

row.forEach( (strElement:string) => {

   strElement = strElement.replace(/\r?\n|\r/g, " "); // replace \n

   fs.appendFileSync(strFilename, strElement+',');

});

fs.appendFileSync(strFilename, '\n');


  });

}

  1. [typescript, file, csv] How to write to csv file -- table2Csv (view)

  2. [file, append, sync] How to write data to file, in sync (ref)


import fs from 'fs'

saveToAudioFile(strFilenameAudio:string, bufAudioChunk:Buffer){

        try{

            fs.appendFileSync(strFilenameAudio, bufAudioChunk);

          } catch (err:any){

                        throw err;

        }

}

  1. [file, append, async] How to write data to file, in async


import fs from 'fs'

saveToAudioFile(strFilenameAudio:string, bufAudioChunk:Buffer){
    let streamFile:WriteStream = fs.createWriteStream(strFilenameAudio, {flags:'a'});

        let streamFile:

        streamFile.write(bufAudioChunk, (err:any) => {

         if (err) {     

              throw err;

          }

      });

   streamFile.close();

}




1.16. Log

  1. [log, console] How to use console.trace() (ref)

  2. [log, console, level] How to use logging level 


console.debug(), console.warn() and console.error()


  1. [log, console, css] How to style your message  (ref) (example)


Key:

console.log(

    "%c%s%c%s",

    "color:white; background:dodgerblue",

    "Hello"

);


  1. [log, winston, instsall] How to use winston for the typescript app  (ref), (more) (view)


npm install winston


  1. [log, winston] How to clean the log file when start (ref)


Key:

Options:{flag: 'w'}


Detail

transports: [

        new winston.transports.File({ filename: 'error.log', level: 'error', options:{flag: 'w'} }),

        new winston.transports.File({ filename: 'combined.log', options:{flag: 'w'} }),

    ],


  1. [log, winston, browser] How to use winston log in browser (ref)

  2. [log, winston] How to silent the log (ref)


Key:

public static logger = winston.createLogger({

    silent: true,

    level: 'info',

   ...

}


1.17. Newtork

  1. [typescript, adaptor] How to get network adaptor name (view)

  2. [typescript, ip] How to get ip address (view)

1.18. Signal

  1. [random] How to generate a random data in [-1, +1]


function __genRandomData():Float32Array{

        let length:number = 44100;

        let floatRawArray:Float32Array = new Float32Array(length);


        for(let i = 0; i<length; i++){

            floatRawArray[i] = Math.random() * 2 - 1; // Math.random() is in [0; 1.0], audio needs to be in [-1.0; 1.0]

        }


        return floatRawArray;

    }


  1. [typescript, signal] How to generate one second sin data with sampling rate 44100 in frequency 1K Hz.


function __genSinData():Float32Array{

        const numSamplingRate:number = 44100;

        const numfrequency:number = 1000;

        const numSec:number = 1;

        const numLength:number = numSec * numSamplingRate;

        

        let floatRawArray:Float32Array = new Float32Array(numLength);

        const secondsPerSample = 1 / numSamplingRate;

        const twoPi = 2 * Math.PI;


        let time = 0;

        for(let i = 0; i<length; i++, time += secondsPerSample){

            floatRawArray[i] = Math.sin(twoPi * numfrequency * time) * 1.0; 

        }


        return floatRawArray;

    }





2. JavaScript

  1. [javascript, style] Node coding style (view), (google), Naming Rule  (ref

  2. [javascript, ecma] ECMAScript 6 (ref)

  3. [javascript] JavaScript Core (ref)

  4. [javascript, doc] jsdoc generator (ref)

  5. [javascript, function] How to write a function


function myfun() {

    return 1234

}

  1. [javscript, exception, safe throw] How to use safe throw in node (view)


2.1. Debug

  1. [javascript, vscode] How to debug the javascript using vscode when you got unboundary break points (ref)


Cause

Debug > Javascript: Use Preview which  causes breakpoints to not hit by debugger

Resolution

[File] ->[Preferences] -> [Settings]:: debug.javascript.usePreview:false


2.2. Variable

  1. [var, int] interger to lowbyte and high byte (view)

  2. [var, NaN] How to determine a NaN value


if (isNaN(x)){

        throw 'Error: x is NaN.';

    }


  1. [var, type] How to determine a variable if it is an 'Uint8Array' array (ref)


Key:

       if(data2.constructor ===  Uint8Array)


Code 

        const data2 = new Uint8Array([104, 101, 108, 108, 111]); // 'Hello World'

        if(data2.constructor ===  Uint8Array){

            document.write('Uint8Array');

        }else{

            document.write('not Uint8Array');

        }


Result

      Uint8Array


  1. [var, null] How to determine null


if(x === null){

    throw 'x === null';

}

2.3. Class

  1. [class, definition] How to define a class (view)

  2. [class, member variable] How to add an new public member variable to your object (view)


class MyClass{

    constructor(){

        this.member = 123;  // <---- add a public member variable

    }

}


  1. [class, private/priviledged member] How to add private member and priviledge member to your class (view)


class MyClass {

    // 建構子

  constructor(){

         ...

        this.myPublicVariable = 123; // <-- public variable

        let myPrivateVariable = 123;   // <--- private variable

        

        function privateMethod(){       // <--- private method

                      myPrivateVariable++;

        }


       this.myPrivilegedMethod = function () { // <-- 特權 method

                       myPrivateVariable++;

        }


  } //end of constructor


  normalMethod(){                           // <-- a public method

       console.log('Normal');


  }

}


  1. [class, static const] How to define a static const class member variable (view)

  2. [class, static, method] How to define a static method 


// File: myclass.js

class MyClass{

    static myStaticMethod(){

         return "hello";

    }

}


// File: testmyclass.js

'use strict';

const Util = require('./myclass);

Util.myStaticMethod();


  1. [class, override] How to override the base class's method  (view)

  2. [class, polymorphism] How to transfer type for an object (view)

  3. [class, old] How to define a class -- OLD Style (view)

  4. [class, callback and bind] How to bind the "this" reference for your callback function (view)

  5. [class, name] How to get the class name (ref)


console.log('this.constructor.name = ', this.constructor.name);


2.4. Module

  1. [module, class] How to create a class module (view)


module.exports = class MyClassName {

  constructor (strClientID) {

     

  }


  publicMethod(strTopic) {

    ...

  }

} // end of class



class MyClassName {

  constructor (strClientID) {

     

  }


  publicMethod(strTopic) {

    ...

  }

} // end of class


module.exports = MyClassName;

2.5. Function

  1. [node, function] How to create an anonymous function


Key:

function() {

   ...

}


Example:

setTimeout(function () {

    console.log('Execute later after 1 second')

}, 1000);


  1. [node, function] What is the arrow function (ref)

  2. [node, function] What is the different between anonymous and arrow functions (ref)


While anonymous (and all traditional JavaScript functions) create their own this bindings, arrow functions inherit the this binding of the containing function.

  1. [node, function, return] How to return multiple value for javascript function


Unlike Python, you cannot return multiple values for a javascript function. However, you can return an array to do the same thing in Python.


Ex:

function myFunction() {

    return [0, 'ok'];

}

let [bOk, strMsg] = myFunction();

if(bOk){

    console.log('bOk =', 1);

}else{

    console.log('bOk =', 0);

}



2.6. I/O

  1. [print, console] How to print out the string


console.log('data = ', buffer)


  1. [print, console, hex] How to show the value in hex (view)

  2. [print, sprintf] How to format your output (view)

  3. [stdin, read] How to read stdin (view)

  4. [node, file, read] How to read text file (view)

  5. [node, file, read, sync] How to read text file in sync mode (ref)


var fs = require('fs');


strFullFilename = './ImperialMarch60_mono_signed_16bit_22k.wav';

this.byteBuffer_ = fs.readFileSync(strFullFilename);

console.log('  this.byteBuffer_ byteLength = ',  this.byteBuffer_.byteLength);

console.log('  this.byteBuffer_ length = ',  this.byteBuffer_.length);

console.log(' this.byteBuffer_ = ',  this.byteBuffer_);



  1. [node, file, read, async] How to read a binary file in async style (ref)


// This will call your callback over and over again until it has finished reading
// the file, so you don't have to block.

// Ref: https://stackoverflow.com/questions/36141452/how-to-read-large-binary-files-in-node-js-without-a-blocking-loop


var fs = require('fs');


var readStream = fs.createReadStream('./test.exe');

readStream.on('data', function (chunk) {

  console.log(chunk.length);

})



  1. [node, file, write] How to write a text file (view)

  2. [node, file, append] How to append a text file (view)


# sync version: text file ,write append.

const fs = require('fs');

fs.appendFileSync('/home/imedi-sns-bk/helloworld.txt', 'Start Debug');


# ansync version: text file, write append.

const fs = require('fs');

fs.appendFile('/home/imedi-sns-bk/helloworld.txt', 'Start Debug', function (err) {

  if (err) throw err;

  console.log('Saved!');

});



// async version: binary file, write append.

const fs = require('fs');

let bufferFrame =new Buffer.alloc(128);

// ...


var stream = fs.createWriteStream("audio.raw", {flags:'a'});

stream.write(bufferFrame, function (err) {

      if (err) throw err;

     console.log('Saved!');

 });


stream.close();

console.log('enqueue:: bufferFrame.length = ', bufferFrame.length);



  1. [node, file, tutorial] A tutorial of file system, watcher (slides)

  2. [path, create] How to create a folder (ref)

  3. [path, info] How to get the absolute full filename -- resolve (view)

  4. [json, obj] How to generate a json string  for an object and restore it (view)

  5. [json, obj array]  How to generate a single JSON string for objects and then restore them  (view)  (ref)

  6. [hw, mac] How to get the mac address -- (view)

  7. [csv, read, code] How to read a csv and generate a hardcode array (view)

  8. [csv, read] How to read a csv file (view)

  9. [csv, read, sync] csv file to array, sync version (view) -- CSV2Array

  10. [csv, write] How to write an array value to csv file (view)

  11. [csv, write, sync] Array 2 CSV (view) -- ArrayCSV

2.7. Async

  1. [generator, simple] 最簡單的 node generator yield 範例 (view)

  2. [generator, write/read] [generator, write/read] How to use generator to handle async write/read sync issue (view)


2.8. Loop

  1. [do-while] How to use do-while (ref)

  2. [switch, range] How to write switch-case (ref)

2.9. Array

  1. [vector] How to create a vector -- new vector() (view)

  2. [array, create, type] How to create a int array (ref)


var int16SampleBuffer = new Int16Array(numOfSample);


  1. [array, append] How to append an element to array -- push(x)  (ref)

  2. [array, concate] How to concate two arrays (ref)


const array3 = array1.concat(array2);


  1. [array, clone] How to clone an array (ref)


samples.slice(i - intWindow, i)


  1. [array, column] How to get a column vector from a 2D array (view)

  2. [array, crop] How to crop a 2D array (view)

  3. [array, normalization] How to normaliztion a 1D array (view)

  4. [array, scale] How to scale all value of a 2D array to new range (view)

  5. [array, stddev] How to get the stddev from an array (view)

  6. [array, gussian] How to get the gussian distribution from a given array (view)

  7. [array, histogram] How to get the histogram from a 1D array (view)

  8. [array, histogram, ascii, show] How to create an ascii histogram (view)

  9. [array, 2d, histogram] How to get the histogram from a 2D array (view)

  10. [array, median] How to calcuate median from an array (ref)

  11. [array, associate] How to use associate array (view)

  12. [array, random, int] How to generate integer random number between a low and high values (view)

  13. [array, median] How to calcauate the median value from any array (ref)


//#Source https://bit.ly/2neWfJ2 

const median = arr => {

  const mid = Math.floor(arr.length / 2),

    nums = [...arr].sort((a, b) => a - b);

  return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;

};

console.log(median([5, 6, 50, 1, -5]));

console.log(median([1, 2, 3, 4, 5]));


  1. [uint8array2hexstring] How to convert an uint8array to hex string (ref)


function toHexString(byteArray) {

    return Array.prototype.map.call(byteArray, function(byte) {

      return ('0' + (byte & 0xFF).toString(16)).slice(-2);

    }).join('');

  }


  1. [hexstring2uint8array] How to convert a hex string to uint8array (ref)


function toByteArray(hexString) {

  var result = [];

  for (var i = 0; i < hexString.length; i += 2) {

    result.push(parseInt(hexString.substr(i, 2), 16));

  }

  return result;

}



2.10. Object inspect

  1. [object, inspect] How to use util.inspect, console.log("string = " , object);  (view)