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
[typescripobject, doc, official] typedoc (ref)
[typescript, doc, handbook] The typescript handbook (ref)
[typescript, tool, play] Online playground (ref)
[typescript, tool, node] ts-node (ref)
[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 |
[typescript, init, tsconfig] How to build tconfig.json (ref)
[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" ] } |
[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 |
[typescript, decorators] decoratorts (ref)
[typescript, clean] How to clean the unnecessary files, makeclean (view) (ref)
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 '{}' + |
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" }
|
[typescript, config] How to implement config (view)
1.1. Debug
[typescript, vscode] How to setup a standard launch.json for typescript (view)
// launch.json "program": "${workspaceFolder}/index.ts", "preLaunchTask": "tsc: build - tsconfig.json", |
[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
[typescript, import] A collection of import packages
import {JSDOM} from 'jsdom'; import cheerio from 'cheerio';
import fs = require('fs'); import https = require('https'); |
[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
[operator] All operators (ref)
[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
|
[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
[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
[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: |
[typescript, variable, undefined] How to determine a variable whether undefined
if (typeof strData === 'undefined'){ return; } |
[typescript, variable] What is the ComputedPropertyName (mdn)(1380)
Why we need to put e.target.name in square brackets []? [duplicate]
[typescript, global] How to use global variable (view)
1.6. Binary data buffer
1.6.1. ArrayBuffer
[typescript, ArrayBuffer] The definition of ArrayBuffer (ref)
a generic, fixed-length raw binary data buffer
[typescript, ArrayBuffer, typedArray2ArrayBuffer] How to convert typed array to ArrayBuffer (ref)
[typescript, ArrayBuffer, ArrayBuffer2int16Array] How to convert ArrayBuffer to typed array (ref)
let byteArray:ArrayBuffer = new ArrayBuffer(10); ... let viewArray:Int16Array = new Int16Array(byteArray); |
[typescript, ArrayBuffer, ArrayBuffer2Buffer] How to conver ArrayBuffer variable to Buffer class instance (ref)
Buffer.from(arrayBufferData); |
1.6.2. TypedArray
[typescript, typedarray] The definition of TypedArray (ref)
an array-like view of an underlying binary data buffer.
[typescript, typedArray2Buffer] How to conver a typed array to Buffer
int16Array2Buffer(int16Array:Int16Array):ArrayBuffer { return Buffer.from(int16Array.buffer); }
|
[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]
|
[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)
Buffer objects are used to represent a fixed-length sequence of bytes. (See Nodejs Buffer section.)
1.7. Array
[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' |
[typescript, array, init] How to create an array initilized with zero values
let numArray:Array<number> = new Array<number>(100).fill(0); |
[typescript, array, spread] What is [...obj] means? (ref)
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 |
[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(); }); |
[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] |
[typescript, array, add, insert first] How to add values of an array to the beginning of an array without creating a new array (ref)
[typescript, arra, delete first] How to remove values of the array in place
buffer.splice(0, newDataChunk.length); // 滑動 (從開頭剪掉資料) |
[typescript, array, queue]
把 陣列 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.8. Character
[char, ascii] How to conver a character to ascii (ref)
let buff:Buffer = 'xxxxx' buff[0] == 'i'.charCodeAt(0) |
1.9. String
[string, \n] How to remove new line in string
strElement = strElement.replace(/\r?\n|\r/g, " "); // replace \n |
[string, include] How to determine a substring wether in a string? (ref)
if (localName.includes('DeviceJing')){ console.log('found target') }
|
[string, endsWith] How to check the string ends with the characters (ref)
if (strFullFilename.endsWith('.raw')){ offset = 0; } |
1.10. Loop
[for in and for of) (view)
1.11. Function
[typescript, callback] How to declare a callback function (ref)
interface Mytype { (msg: string): void; }
function sayHi(cb: Mytype) { cb('Hi!') } |
[typescript, function, return] How to return an array
function myFun():Array<any> { ... return [data1, data2]; }
// Usage [data1, data2] = myFun(); |
[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); |
[typescript, function, static var] How to declare static variable in function (ref)
[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
|
[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
[typescript, class, constructor] How to create and assign a class instance property from a constructor parameter (ref)
short-cut
class MyClass{ constructor(public myPublicVar:MyType, normalArg){ }
myMethod(){ this.myPublicVar = ...; this.normalArg = ...; // Error: there is no normalArg property } } |
Traditional way
class MyClass{ public myPublicVar:MyType = new MyType(); constructor(normalArg){ this.normalArg = ...; // Error: there is no normalArg property }
myMethod(){ this.myPublicVar = ...; } } |
[typescript, class, member] How to declare a constant member in class (ref)
export class MyClass { readonly data:number = 123; } |
[typescript, class, method, static] How to declare a static method in Typescript
export class MyClass { static method(){ } } |
[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
[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; }
|
[typescript, type alias, function] Alias a function type
// 重新命名一個新的 type 為 func. // 內容為 一個 function, 傳回字串型態 type func = () => string; |
[typescript, object type] How to use the object type (view), (ref)
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; } |
[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);
|
[typescript, object type] How to print object type variable (view)
console.log('/increase. status = ' + JSON.stringify(status)); |
[typescript, object type] How to use option parameters (ref)
[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();
|
[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]); } } } |
[typescript, property] What is the ES6 computed property (ref)
var obj = {}; OR var car = {type:"Fiat", model:"500", color:"white"};
|
[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
|
[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
[typescript, mapped, doc] Mapped Types (ref)
[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
[typescript, file, remove] How to remove a file
fs.unlinkSync(strFilename); // remove the file |
[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');
}); } |
[typescript, file, csv] How to write to csv file -- table2Csv (view)
[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; } } |
[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
[log, console] How to use console.trace() (ref)
[log, console, level] How to use logging level
console.debug(), console.warn() and console.error() |
[log, console, css] How to style your message (ref) (example)
Key: console.log( "%c%s%c%s", "color:white; background:dodgerblue", "Hello" ); |
[log, winston, instsall] How to use winston for the typescript app (ref), (more) (view)
[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'} }), ], |
[log, winston, browser] How to use winston log in browser (ref)
[log, winston] How to silent the log (ref)
Key: public static logger = winston.createLogger({ silent: true, level: 'info', ... } |
1.17. Newtork
[typescript, adaptor] How to get network adaptor name (view)
[typescript, ip] How to get ip address (view)
1.18. Signal
[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; }
|
[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
[javascript, style] Node coding style (view), (google), Naming Rule (ref)
[javascript, ecma] ECMAScript 6 (ref)
[javascript] JavaScript Core (ref)
[javascript, doc] jsdoc generator (ref)
[javascript, function] How to write a function
function myfun() { return 1234 } |
[javscript, exception, safe throw] How to use safe throw in node (view)
2.1. Debug
[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
[var, int] interger to lowbyte and high byte (view)
[var, NaN] How to determine a NaN value
if (isNaN(x)){ throw 'Error: x is NaN.'; }
|
[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 |
[var, null] How to determine null
if(x === null){ throw 'x === null'; } |
2.3. Class
[class, definition] How to define a class (view)
[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 } } |
[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');
} } |
[class, static const] How to define a static const class member variable (view)
[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(); |
[class, override] How to override the base class's method (view)
[class, polymorphism] How to transfer type for an object (view)
[class, old] How to define a class -- OLD Style (view)
[class, callback and bind] How to bind the "this" reference for your callback function (view)
[class, name] How to get the class name (ref)
console.log('this.constructor.name = ', this.constructor.name); |
2.4. Module
[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
[node, function] How to create an anonymous function
Key: function() { ... }
Example: setTimeout(function () { console.log('Execute later after 1 second') }, 1000);
|
[node, function] What is the arrow function (ref)
[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. |
[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
[print, console] How to print out the string
console.log('data = ', buffer) |
[print, console, hex] How to show the value in hex (view)
[print, sprintf] How to format your output (view)
[stdin, read] How to read stdin (view)
[node, file, read] How to read text file (view)
[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_);
|
[node, file, read, async] How to read a binary file in async style (ref)
[node, file, write] How to write a text file (view)
[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);
|
[node, file, tutorial] A tutorial of file system, watcher (slides)
[path, create] How to create a folder (ref)
[path, info] How to get the absolute full filename -- resolve (view)
[json, obj] How to generate a json string for an object and restore it (view)
[json, obj array] How to generate a single JSON string for objects and then restore them (view) (ref)
[hw, mac] How to get the mac address -- (view)
[csv, read, code] How to read a csv and generate a hardcode array (view)
[csv, read] How to read a csv file (view)
[csv, read, sync] csv file to array, sync version (view) -- CSV2Array
[csv, write] How to write an array value to csv file (view)
[csv, write, sync] Array 2 CSV (view) -- ArrayCSV
2.7. Async
[generator, simple] 最簡單的 node generator yield 範例 (view)
[generator, write/read] [generator, write/read] How to use generator to handle async write/read sync issue (view)
2.8. Loop
[do-while] How to use do-while (ref)
[switch, range] How to write switch-case (ref)
2.9. Array
[vector] How to create a vector -- new vector() (view)
[array, create, type] How to create a int array (ref)
var int16SampleBuffer = new Int16Array(numOfSample); |
[array, append] How to append an element to array -- push(x) (ref)
[array, concate] How to concate two arrays (ref)
const array3 = array1.concat(array2); |
[array, clone] How to clone an array (ref)
samples.slice(i - intWindow, i) |
[array, column] How to get a column vector from a 2D array (view)
[array, crop] How to crop a 2D array (view)
[array, normalization] How to normaliztion a 1D array (view)
[array, scale] How to scale all value of a 2D array to new range (view)
[array, stddev] How to get the stddev from an array (view)
[array, gussian] How to get the gussian distribution from a given array (view)
[array, histogram] How to get the histogram from a 1D array (view)
[array, histogram, ascii, show] How to create an ascii histogram (view)
[array, 2d, histogram] How to get the histogram from a 2D array (view)
[array, median] How to calcuate median from an array (ref)
[array, associate] How to use associate array (view)
[array, random, int] How to generate integer random number between a low and high values (view)
[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]));
|
[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(''); }
|
[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
[object, inspect] How to use util.inspect, console.log("string = " , object); (view)