1# ets_utils 2The ets_utils component provides four modules: js_api_module, js_util_module, js_sys_module, and js_concurrent_module. The following provides an introduction to these modules and describes their directory structures, APIs, and involved repositories. 3 4# Modules 5## js_api_module 6### Introduction 7 8The js_api_module provides the following classes:<br>**URL**: provides APIs to parse, construct, standardize, and encode URLs. The constructor of this class creates a **URL** object, where you can call APIs to parse and change the URL. **URLSearchParams**: provides APIs to handle URL query strings. 9 10**URI**: provides APIs to parse URI strings. 11 12**ConvertXml**: provides APIs to convert XML text into JavaScript objects. 13 14**XmlSerializer**: provides APIs to generate an XML file. The constructor of this class creates an **XmlSerializer** object, where you can call the APIs to generate an XML file. **XmlPullParser**: provides APIs to parse an XML file. The constructor of this class creates an **XmlPullParser** object, where you can call the APIs to parse an XML file. 15 16### Directory Structure 17 18``` 19commonlibrary/ets_utils/js_api_module/ 20├── Class:URL # URL class 21│ ├── new URL(input[, base]) # Used to create a URL object 22│ ├── hash # hash attribute 23│ ├── host # host attribute 24│ ├── hostname # hostname attribute 25│ ├── href # href attribute 26│ ├── origin # origin attribute 27│ ├── password # password attribute 28│ ├── pathname # pathname attribute 29│ ├── port # port attribute 30│ ├── protocol # protocol attribute 31│ ├── search # search attribute 32│ ├── searchParams # searchParams attribute 33│ ├── username # username attribute 34│ ├── toString() # toString method 35│ └── toJSON() # toJSON method 36├── Class: URLSearchParams # URLSearchParams class 37│ ├── new URLSearchParams() # Used to create a URLSearchParams object 38│ ├── new URLSearchParams(string) # Used to create a URLSearchParams object 39│ ├── new URLSearchParams(obj) # Used to create a URLSearchParams object 40│ ├── new URLSearchParams(iterable) # Used to create a URLSearchParams object 41│ ├── append(name, value) # append method 42│ ├── delete(name) # delete method 43│ ├── entries() # entries method 44│ ├── forEach(fn[, thisArg]) # forEach method 45│ ├── get(name) # get method 46│ ├── getAll(name) # getAll method 47│ ├── has(name) # has method 48│ ├── keys() # keys method 49│ ├── set(name, value) # set method 50│ ├── sort() # sort method 51│ ├── toString() # toString method 52│ ├── values() # values method 53│ └── urlSearchParams[Symbol.iterator]() # Used to create a URLSearchParams object 54├── Class:URI # URI class 55│ ├── URI(str: string) # Used to create a URI object 56│ ├── scheme # scheme attribute 57│ ├── authority # authority attribute 58│ ├── ssp # ssp attribute 59│ ├── userinfo # userinfo attribute 60│ ├── host # host attribute 61│ ├── port # port attribute 62│ ├── query # query attribute 63│ ├── fragment # fragment attribute 64│ ├── path # path attribute 65│ ├── equals(ob: Object) # equals attribute 66│ ├── normalize() # normalize attribute 67│ ├── checkIsAbsolute() # checkIsAbsolute attribute 68│ ├── normalize() # normalize method 69│ └── toString() # toString method 70├── Class:ConvertXml # ConvertXml class 71│ ├── ConvertXml() # Used to create a ConvertXml object 72│ └── convert(xml: string, options: Object) # convert method 73├── Class:XmlSerializer # XmlSerializer class 74│ ├── new XmlSerializer(buffer: ArrayBuffer | DataView, encoding?: string) # Used to create an XmlSerializer object 75│ ├── setAttributes(name: string, value: string) # setAttributes method 76│ ├── addEmptyElement(name: string) # addEmptyElement method 77│ ├── setDeclaration() # setDeclaration method 78│ ├── startElement(name: string) # startElement method 79│ ├── endElement() # endElement method 80│ ├── setNamespace(prefix: string, namespace: string) # setNamespace method 81│ ├── setComment(text: string) # setComment method 82│ ├── setCData(text: string) # setCData method 83│ ├── setText(text: string) # setText method 84│ └── setDocType(text: string) # setDocType method 85└── Class: XmlPullParser # XmlPullParser class 86 ├── new (buffer: ArrayBuffer | DataView, encoding?: string) # Used to create an XmlPullParser object 87 └── parse(option: ParseOptions) # parse method 88``` 89 90### Usage 91 92#### Available APIs 93 94 95| API| Description| 96| -------- | -------- | 97| URL(url: string,base?:string \| URL) | Creates a **URL** object that references a URL specified using an absolute URL string, a relative URL string, and a base URL string.| 98| tostring():string | Converts the parsed URL into a string. Its function is the same as that of read-only **URL.href**.| 99| toJSON():string | Converts the parsed URL into a JSON string.| 100| new URLSearchParams() | No-argument constructor that creates a **URLSearchParams** object. The question mark (?) at the beginning of the query string will be ignored.| 101| new URLSearchParams(string) | Constructor that creates a **URLSearchParams** object with the string type specified. The question mark (?) at the beginning of the query string will be ignored.| 102| new URLSearchParams(obj) | Constructor that creates a **URLSearchParams** object with the object type specified. The question mark (?) at the beginning of the query string will be ignored.| 103| new URLSearchParams(iterable) | Constructor that creates a **URLSearchParams** object with the iterable type specified. The question mark (?) at the beginning of the query string will be ignored.| 104| has(name: string): boolean | Checks whether a key in this **URLSearchParams** object has a value. It returns **true** if the key has a value and returns **false** otherwise.| 105| set(name: string, value string): void | Sets the value for a key in this **URLSearchParams** object. If key-value pairs matching the specified key exist, the value of the first occurrence of the key-value pair will be changed to the specified value and other key-value pairs will be deleted. Otherwise, the key-value pair will be appended to the query string.| 106| sort(): void | Sorts all key-value pairs in this **URLSearchParams** object based on the Unicode code points of the keys and returns **undefined**. | 107| toString(): string | Obtains strings that can be used for URL query based on this **URLSearchParams** object.| 108| keys(): iterableIterator\<string> | Obtains an iterator that contains the keys of all the key-value pairs in this **URLSearchParams** object.| 109| values(): iterableIterator\<string> | Obtains an iterator that contains the values of all the key-value pairs in this **URLSearchParams** object.| 110| append(name: string, value: string): void | Appends a key-value pair into this **URLSearchParams** object.| 111| delete(name: string): void | Deletes key-value pairs of the specified key from this **URLSearchParams** object.| 112| get(name: string): string | Obtains the value of the first key-value pair with the specified key in this **URLSearchParams** object.| 113| getAll(name: string): string[] | Obtains all the key-value pairs with the specified key in this **URLSearchParams** object.| 114| entries(): iterableIterator<[string, string]> | Obtains an iterator that contains all the key-value pairs of this **URLSearchParams** object.| 115| forEach(): void | Traverses the key-value pairs in this **URLSearchParams** object by using a callback.| 116| urlSearchParams\[Symbol.iterator]() | Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and each array contains a key and value.| 117| URI(str: string) | Constructs a URI by parsing the given input parameter according to the syntax specified in Appendix A of RFC 2396.| 118| scheme | Obtains the scheme component of this URI; returns **null** if **scheme** is not defined.| 119| authority | Obtains the decoded authority component of this URI; returns **null** if **authority** is not defined.| 120| ssp | Obtains the decoded scheme-specific component of this URI.| 121| userinfo | Obtains the decoded userinfo component of this URI. The return value contains password and username.| 122| host | Obtains the host component of this URI; returns **null** if **host** is not defined.| 123| port | Obtains the port component of this URI; returns **-1** if **port** is not defined. The return value is a non-negative integer.| 124| query | Obtains the query component of this URI; returns **null** if **query** is not defined.| 125| fragment | Obtains the decoded fragment component of this URI; returns **null** if **fragment** is not defined.| 126| path | Obtains the decoded path component of this URI; returns **null** if **path** is not defined.| 127| equals(ob: Object) | Checks whether this URI is the same as another URI object. It immediately returns **false** if the given object is not a URI.| 128| normalize() | Normalizes the path of this URI. It constructs a new URI object if the path of the URI is not standard.| 129| checkIsAbsolute() | Checks whether this URI is an absolute URI (whether the scheme component is defined). It returns **true** if the URI is an absolute URI; otherwise, it returns **false**.| 130| ConvertXml() | A no-argument constructor that creates a **ConvertXml** object. | 131| convert(xml: string, options: Object) | Converts an XML text into a JavaScript object.| 132| XmlSerializer(buffer: ArrayBuffer \| DataView, encoding?: string) | Creates and returns an **XmlSerializer** object. The **XmlSerializer** object passes two parameters. The first parameter is the memory of the **ArrayBuffer** or **DataView** type, and the second parameter is the file format (UTF-8 by default).| 133| setAttributes(name: string, value: string): void | Sets attributes for the XML file.| 134| addEmptyElement(name: string): void | Adds an empty element.| 135| setDeclaration(): void | Sets a declaration for the XML file. Example: <? xml version="1.0"encoding="utf-8">| 136| startElement(name: string): void | Writes the start tag based on the given element name.| 137| endElement(): void | Writes the end tag of the element.| 138| setNamespace(prefix: string, namespace: string): void | Sets the namespace for an element tag.| 139| setComment(text: string): void | Sets the comment.| 140| setCData(text: string): void | Sets the **CData** attribute.| 141| setText(text: string): void | Sets the **Text** attribute.| 142| setDocType(text: string): void | Sets the **DocType** attribute.| 143| XmlPullParser(buffer: ArrayBuffer \| DataView, encoding?: string) | Creates and returns an **XmlPullParser** object. The **XmlPullParser** object passes two parameters. The first parameter is the memory of the **ArrayBuffer** or **DataView** type, and the second parameter is the file format (UTF-8 by default).| 144| parse(option: ParseOptions): void | Parses XML information. **ParseOptions** contains five optional parameters: {supportDoctype?: boolean ignoreNameSpace?: boolean tagValueCallbackFunction?: (name: string, value: string) => boolean attributeValueCallbackFunction?: (name: string, value: string) => boolean) tokenValueCallbackFunction?: (eventType: EventType, value: ParseInfo) => boolean }. For **tokenValueCallbackFunction**, the first input parameter indicates the event type, and the second input parameter indicates the **info** interface that contains getters such as **getColumnNumber** and **getDepth**. You can use methods such as **info.getDepth()** to obtain information during the parsing.| 145#### How to Use 146 147Use the APIs as follows: 148 149 1501. new URL(url: string,base?:string|URL) 151``` 152let b = new URL('https://developer.mozilla.org'); // => 'https://developer.mozilla.org/' 153 154let a = new URL( 'sca/./path/path/../scasa/text', 'http://www.example.com'); 155// => 'http://www.example.com/sca/path/scasa/text' 156``` 1572. tostring():string 158``` 159const url = new URL('http://10.0xFF.O400.235:8080/directory/file?query#fragment'); 160url.toString() // => 'http://10.0xff.o400.235:8080/directory/file?query#fragment' 161 162const url = new URL("http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"); 163url.toString() // => 'http://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]/index.html' 164 165const url = new URL("http://username:password@host:8080/directory/file?query#fragment"); 166url.toString() // => 'http://username:password@host:8080/directory/file?query#fragment' 167``` 1683. toJSON():string 169``` 170const url = new URL("https://developer.mozilla.org/en-US/docs/Web/API/URL/toString"); 171url.toJSON(); // => 'https://developer.mozilla.org/en-US/docs/Web/API/URL/toString' 172``` 1734. new URLSearchParams() 174``` 175let params = new URLSearchParams('foo=1&bar=2'); 176``` 1775. new URLSearchParams(string) 178``` 179params = new URLSearchParams('user=abc&query=xyz'); 180console.log(params.get('user')); 181// Prints 'abc' 182``` 1836. new URLSearchParams(obj) 184``` 185const params = new URLSearchParams({ 186 user: 'abc', 187 query: ['first', 'second'] 188}); 189console.log(params.getAll('query')); 190// Prints [ 'first,second' ] 191``` 1927. new URLSearchParams(iterable) 193``` 194let params; 195 196// Using an array 197params = new URLSearchParams([ 198 ['user', 'abc'], 199 ['query', 'first'], 200 ['query', 'second'], 201]); 202console.log(params.toString()); 203// Prints 'user = abc & query = first&query = second' 204``` 2058. has(name: string): boolean 206``` 207console.log(params.has('bar')); // =>true 208``` 2099. set(name: string, value string): void 210``` 211params.set('baz', 3); 212``` 21310. sort(): void 214``` 215params .sort(); 216``` 21711. toString(): string 218``` 219console.log(params .toString()); // =>bar=2&baz=3&foo=1' 220``` 22112. keys(): iterableIterator\<string> 222``` 223for(var key of params.keys()) { 224 console.log(key); 225} // =>bar baz foo 226``` 22713. values(): iterableIterator\<string> 228``` 229for(var value of params.values()) { 230 console.log(value); 231} // =>2 3 1 232``` 23314. append(name: string, value: string): void 234``` 235params.append('foo', 3); // =>bar=2&baz=3&foo=1&foo=3 236``` 23715. delete(name: string): void 238``` 239params.delete('baz'); // => bar=2&foo=1&foo=3 240``` 24116. get(name: string): string 242``` 243params.get('foo'); // => 1 244``` 24517. getAll(name: string): string[] 246``` 247params.getAll('foo'); // =>[ '1', '3' ] 248``` 24918. entries(): iterableIterator<[string, string]> 250``` 251for(var pair of searchParams.entries()) { 252 console.log(pair[0]+ ', '+ pair[1]); 253} // => bar, 2 foo, 1 foo, 3 254``` 25519. forEach(): void 256``` 257url.searchParams.forEach((value, name, searchParams) => { 258 console.log(name, value, url.searchParams === searchParams); 259}); 260// => foo 1 true 261// => bar 2 true 262``` 26320. urlSearchParams[Symbol.iterator]() 264``` 265const params = new URLSearchParams('foo=bar&xyz=baz'); 266for (const [name, value] of params) { 267 console.log(name, value); 268} 269// Prints: 270// foo bar 271// xyz bar 272``` 273 274 27521. URI(str: string) 276``` 277let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 278``` 27922. scheme 280``` 281let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 282gaogao.scheme // => "http"; 283``` 28423. authority 285``` 286let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 287gaogao.authority // => "gg:gaogao@www.baidu.com:99"; 288``` 28924. ssp 290``` 291let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 292gaogao.ssp " // => gg:gaogao@www.baidu.com:99/path/path?query"; 293``` 29425. userinfo 295``` 296let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 297gaogao.userinfo // => "gg:gaogao"; 298``` 29926. host 300``` 301let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 302gaogao.host // => "www.baidu.com"; 303``` 30427. port 305``` 306let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 307gaogao.port // => "99"; 308``` 30928. query 310``` 311let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 312gaogao.query // => "query"; 313``` 31429. fragment 315``` 316let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 317gaogao.fragment // => "fagment"; 318``` 31930. path 320``` 321let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 322gaogao.path // => "/path/path"; 323``` 32431. equals(ob: Object) 325``` 326let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path1?query#fagment'); 327let gaogao1 = gaogao; 328let res = gaogao.equals(gaogao1); 329console.log(res); // => true; 330``` 33132. normalize() 332``` 333let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path/66./../././mm/.././path1?query#fagment'); 334let res = gaogao.normalize(); 335console.log(res.path); // => "/path/path1" 336console.log(res.toString()); // => "http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path/path1?query#fagment" 337``` 33833. checkIsAbsolute() 339``` 340let gaogao = new Uri.URI('f/tp://username:password@www.baidu.com:88/path?query#fagment'); 341let res = gaogao.checkIsAbsolute(); 342console.log(res); //=> false; 343``` 34434. toString() 345``` 346let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/../../path/.././../aa/bb/cc?query#fagment'); 347let res = gaogao.toString(); 348console.log(res.toString()); // => 'http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/../../path/.././../aa/bb/cc?query#fagment'; 349``` 350 351 35235. ConvertXml() 353``` 354var convertml = new convertXml.ConvertXml(); 355``` 35636. convert(xml: string, options: Object) 357``` 358var result = convertml.convert(xml, {compact: false, spaces: 4}); 359``` 36037. new XmlSerializer(buffer: ArrayBuffer | DataView, encoding?: string) 361``` 362 363var arrayBuffer = new ArrayBuffer(1024); 364var bufView = new DataView(arrayBuffer); 365var thatSer = new xml.XmlSerializer(bufView); 366``` 36738. setDeclaration(): void 368``` 369var thatSer = new xml.XmlSerializer(bufView); 370thatSer.setDeclaration() // => <?xml version="1.0" encoding="utf-8"?>; 371``` 37239. setComment(text: string):void 373``` 374var thatSer = new xml.XmlSerializer(bufView); 375thatSer.setCommnet("Hello, World!"); // => <!--Hello, World!-->; 376``` 37740. setCData(text: string) :void 378``` 379var thatSer = new xml.XmlSerializer(bufView); 380thatSer.setDocType('root SYSTEM "http://www.test.org/test.dtd"'); // => <![CDATA[root SYSTEM \"http://www.test.org/test.dtd\"]]> 381``` 38241. setDocType(text: string):void 383``` 384var thatSer = new xml.XmlSerializer(bufView); 385thatSer.setDocType("foo"); // => <!DOCTYPE foo> 386``` 38742. setNamespace(prefix: string, namespace: string): void 38843. startElement(name: string): void 38944. setAttributes(name: string, value: string): void 39045. endElement(): void 39146. setText(text: string): void 392``` 393var thatSer = new xml.XmlSerializer(bufView); 394thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); 395thatSer.startElement("table"); 396thatSer.setAttributes("importance", "high"); 397thatSer.setText("Happy"); 398endElement(); // => <h:table importance="high" xmlns:h="http://www.w3.org/TR/html4/">Happy</h:table> 399``` 40047. addEmptyElement(name: string): void 401``` 402var thatSer = new xml.XmlSerializer(bufView); 403thatSer.addEmptyElement("b"); // => <b/> 404``` 40548. new (buffer: ArrayBuffer | DataView, encoding?: string) 406``` 407var strXml = 408 '<?xml version="1.0" encoding="utf-8"?>' + 409 '<note importance="high" logged="true">' + 410 ' <title>Happy</title>' + 411 '</note>'; 412var arrayBuffer = new ArrayBuffer(strXml.length*2); 413var bufView = new Uint8Array(arrayBuffer); 414var strLen = strXml.length; 415for (var i = 0; i < strLen; ++i) { 416 bufView[i] = strXml.charCodeAt(i); // Set the ArrayBuffer mode. 417} 418var that = new xml.XmlPullParser(arrayBuffer); 419 420``` 42149. parse(option: ParseOptions): void 422``` 423var strXml = 424 '<?xml version="1.0" encoding="utf-8"?>' + 425 '<note importance="high" logged="true">' + 426 ' <title>Happy</title>' + 427 '</note>'; 428var arrayBuffer = new ArrayBuffer(strXml.length*2); 429var bufView = new Uint8Array(arrayBuffer); 430var strLen = strXml.length; 431for (var i = 0; i < strLen; ++i) { 432 bufView[i] = strXml.charCodeAt(i); 433} 434var that = new xml.XmlPullParser(arrayBuffer); 435var arrTag = {}; 436arrTag[0] = '132'; 437var i = 1; 438function func(key, value){ 439 arrTag[i] = 'key:'+key+' value:'+ value.getDepth(); 440 i++; 441 return true; 442} 443var options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} 444that.parse(options); 445``` 446 447## js_util_module 448### Introduction 449 450The js_util_module provides the following classes:<br> **TextEncoder**: provides APIs to encode a string into a UTF-8 byte stream. **TextDecoder**: provides APIs to decode a byte stream into a string. **HelpFunction**: provides APIs to perform the callback and promise processing on functions, compile and output error codes, and format class strings. **encode**: provides APIs to use the Base64 encoding scheme to encode all bytes in a Unit8Array typed array into a new Unit8Array typed array or encode a byte array into a string. **decode**: provides APIs to use the Base64 encoding scheme to decode a Base64-encoded string or a Unit8Array typed array into a new Unit8Array typed array. **RationalNumber**: provides APIs to compare rational numbers and obtain numerators and denominators. **LruBuffer**: provides APIs to discard the least recently used data to make rooms for new elements when the buffer is full. The Least Recently Used (LRU) algorithm believes that the recently used data may be accessed again in the near future and the least accessed data is the least valuable data and should be removed from the buffer. **Scope**: provides APIs to define the valid range of a field. The constructor of this class creates comparable objects with lower and upper limits. 451### Directory Structure 452 453``` 454commonlibrary/ets_utils/js_util_module/ 455├── Class:TextEncoder # TextEncoder class 456│ ├── new TextEncoder() # Used to create a TextEncoder object 457│ ├── encode() # encode method 458│ ├── encoding # encoding attribute 459│ └── encodeInto() # encodeInto method 460├── Class:TextDecoder # TextDecoder class 461│ ├── new TextDecoder() # Used to create a TextDecoder object 462│ ├── decode() # decode method 463| ├── decodeWithStream() # decodeWithStream method 464│ ├── encoding # encoding attribute 465│ ├── fatal # fatal attribute 466│ └── ignoreBOM # ignoreBOM attribute 467├── printf() # printf method 468├── getErrorString() # getErrorString method 469├── callbackWrapper() # callbackWrapper method 470├── promiseWrapper() # promiseWrapper method 471├── Class:Base64 # Base64 class 472│ ├── new Base64() # Used to create a Base64 object 473│ ├── encodeSync() # encodeSync method 474│ ├── encodeToStringSync() # encodeToStringSync method 475│ ├── decodeSync() # decodeSync method 476│ ├── encode() # encode method 477│ ├── encodeToString() # encodeToString method 478│ └── decode() # decode method 479├── Class:RationalNumber # RationalNumber class 480│ ├── new RationalNumber() # Used to create a RationalNumber object 481│ ├── createRationalFromString() # createRationalFromString method 482│ ├── compareTo() # compareTo method 483│ ├── equals() # equals method 484│ ├── valueOf() # valueOf method 485│ ├── getCommonDivisor() # getCommonDivisor method 486│ ├── getDenominator() # getDenominator method 487│ ├── getNumerator() # getNumerator method 488│ ├── isFinite() # isFinite method 489│ ├── isNaN() # isNaN method 490│ ├── isZero() # isZero method 491│ └── toString() # toString method 492├── Class:LruBuffer # LruBuffer class 493│ ├── new LruBuffer() # Used to create a LruBuffer object 494│ ├── updateCapacity() # updateCapacity method 495│ ├── toString() # toString method 496│ ├── values() # values method 497│ ├── length # length attribute 498│ ├── getCapacity() # getCapacity method 499│ ├── clear() # clear method 500│ ├── getCreateCount() # getCreateCount method 501│ ├── getMissCount() # getMissCount method 502│ ├── getRemovalCount() # getRemovalCount method 503│ ├── getMatchCount() # getMatchCount method 504│ ├── getPutCount() # getPutCount method 505│ ├── isEmpty() # isEmpty method 506│ ├── get() # get method 507│ ├── put() # put method 508│ ├── keys() # keys method 509│ ├── remove() # remove method 510│ ├── afterRemoval() # afterRemoval method 511│ ├── contains() # contains method 512│ ├── createDefault() # createDefault method 513│ ├── entries() # entries method 514│ └── [Symbol.iterator]() # Symboliterator method 515|—— Class:Scope # Scope class 516| ├── constructor() # Used to create a Scope object 517| ├── toString() # toString method 518| ├── intersect() # intersect method 519| ├── intersect() # intersect method 520| ├── getUpper() # getUpper method 521| ├── getLower() # getLower method 522| ├── expand() # expand method 523| ├── expand() # expand method 524| ├── expand() # expand method 525| ├── contains() # contains method 526| ├── contains() # contains method 527| └── clamp() # clamp method 528└── Class:Types # Types class 529 ├── isAnyArrayBuffer() # isAnyArrayBuffer method 530 ├── isArrayBufferView() # isArrayBufferView method 531 ├── isArgumentsObject() # isArgumentsObject method 532 ├── isArrayBuffer() # isArrayBuffer method 533 ├── isAsyncFunction() # isAsyncFunction method 534 ├── isBigInt64Array() # isBigInt64Array method 535 ├── isBigUint64Array() # isBigUint64Array method 536 ├── isBooleanObject() # isBooleanObject method 537 ├── isBoxedPrimitive() # isBoxedPrimitive method 538 ├── isDataView() # isDataView method 539 ├── isDate() # isDate method 540 ├── isExternal() # isExternal method 541 ├── isFloat32Array() # isFloat32Array method 542 ├── isFloat64Array() # isFloat64Array method 543 ├── isGeneratorFunction() # isGeneratorFunction method 544 ├── isGeneratorObject() # isGeneratorObject method 545 ├── isInt8Array() # isInt8Array method 546 ├── isInt16Array() # isInt16Array method 547 ├── isInt32Array() # isInt32Array method 548 ├── isMap() # isMap method 549 ├── isMapIterator() # isMapIterator method 550 ├── isModuleNamespaceObject() # isModuleNamespaceObject method 551 ├── isNativeError() # isNativeError method 552 ├── isNumberObject() # isNumberObject method 553 ├── isPromise() # isPromise method 554 ├── isProxy() # isProxy method 555 ├── isRegExp() # isRegExp method 556 ├── isSet() # isSet method 557 ├── isSetIterator() # isSetIterator method 558 ├── isSharedArrayBuffer() # isSharedArrayBuffer method 559 ├── isStringObject() # isStringObject method 560 ├── isSymbolObject() # isSymbolObject method 561 ├── isTypedArray() # isTypedArray method 562 ├── isUint8Array() # isUint8Array method 563 ├── isUint8ClampedArray() # isUint8ClampedArray method 564 ├── isUint16Array() # isUint16Array method 565 ├── isUint32Array() # isUint32Array method 566 ├── isWeakMap() # isWeakMap method 567 └── isWeakSet() # isWeakSet method 568``` 569### Usage 570 571#### Available APIs 572 573 574| API| Description| 575| -------- | -------- | 576| constructor(encoding? : string) | A constructor used to create a **TextDecoder** object. **encoding** indicates the encoding format. The default value is **UTF-8**, and the values **gb18030**, **gbk**, and **gb2312** are supported.| 577| readonly encoding : string | Obtains the encoding format. Only **UTF-8** is supported.| 578| encode(input : string) : Uint8Array | Encodes a string into a Uint8Array typed array.| 579| encodeInto(input : string, dest : Uint8Array) : {read : number, written : number} | Encodes a string into a Unit8Array typed array, and stores the array. **dest** indicates the storage location, **read** indicates the number of encoded characters, and **written** indicates the number of bytes occupied by the encoded characters.| 580| constructor(encoding? : string, options? : {fatal? : boolean, ignoreBOM? : boolean}) | A constructor used to create a **TextDecoder** object. **encoding** indicates the decoding format. **options** indicates certain attributes, where **fatal** specifies whether to throw an exception, and **ignoreBOM** specifies whether to ignore the BOM flag.| 581| readonly encoding : string | Obtains the decoding format.| 582| readonly fatal : boolean | Obtains the setting of whether to throw an exception.| 583| readonly ignoreBOM : boolean | Obtains the setting of whether to ignore the BOM flag.| 584| decode(input : Uint8Array, options?: { stream?: false }) : string | Decodes a Unit8Array typed array into a string. **input** indicates the data to decode, and **options** specifies whether additional data will be followed, with the default value **false**.| 585| decodeWithStream(input : Uint8Array, options?: { stream?: false }) : string | Decodes a Unit8Array typed array into a string. **input** indicates the data to decode, and **options** specifies whether additional data will be followed, with the default value **false**.| 586| encodeSync(src: Uint8Array): Uint8Array; | Uses the Base64 encoding scheme to synchronously encode all bytes in a Unit8Array typed array into a new Unit8Array typed array.| 587| encodeToStringSync(src: Uint8Array): string; | Uses the Base64 encoding scheme to synchronously encode a Unit8Array typed array into a string.| 588| decodeSync(src: Uint8Array \| string): Uint8Array; | Uses the Base64 encoding scheme to synchronously decode a Base64-encoded string or a Unit8Array typed array into a new Unit8Array typed array.| 589| encode(src: Uint8Array): Promise\<Uint8Array\>; | Uses the Base64 encoding scheme to asynchronously encode all bytes in a Unit8Array typed array into a new Unit8Array typed array.| 590| encodeToString(src: Uint8Array): Promise\<string\>; | Uses the Base64 encoding scheme to asynchronously encode a Unit8Array typed array into a string. It uses a promise to return the result.| 591| decode(src: Uint8Array \| string): Promise\<Uint8Array\>; | Uses the Base64 encoding scheme to asynchronously decode a Base64-encoded string or a Unit8Array typed array into a new Unit8Array typed array.| 592| static createRationalFromString(rationalString: string): RationalNumber | Creates a **RationalNumber** object based on the given string.| 593| compareTo(another: RationalNumber): number | Compares this **RationalNumber** object with the given object.| 594| equals(obj: object): number | Checks whether this **RationalNumber** object equals the given object.| 595| valueOf(): number | Rounds the value of this **RationalNumber** object as an integer or a floating-point number.| 596| static getCommonDivisor(number1: number, number2: number,): number | Obtains the greatest common divisor of two specified integers.| 597| getDenominator(): number | Obtains the denominator of this **RationalNumber** object.| 598| getNumerator(): number | Obtains the numerator of this **RationalNumber** object.| 599| isFinite(): boolean | Checks whether this **RationalNumber** object represents a finite value.| 600| isNaN(): boolean | Checks whether this **RationalNumber** object is a Not a Number (NaN).| 601| isZero(): boolean | Checks whether this **RationalNumber** object is **0**.| 602| toString(): string | Obtains the string representation of this **RationalNumber** object.| 603| constructor(capacity?: number) | Default constructor used to create an **LruBuffer** instance. The default capacity of the buffer is 64.| 604| updateCapacity(newCapacity: number): void | Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown.| 605| toString(): string | Obtains the string representation of this **LruBuffer** object. | 606| values(): V[] | Obtains all values in this buffer, listed from the most to the least recently used.| 607| length: number | Obtains the total number of values in this buffer.| 608| getCapacity(): number | Obtains the capacity of this buffer.| 609| clear(): void | Clears key-value pairs from this buffer. **afterRemoval()** will be called to perform subsequent operations.| 610| getCreateCount(): number | Obtains the number of return values for **createDefault()**.| 611| getMissCount(): number | Obtains the number of times that the queried values are mismatched.| 612| getRemovalCount(): number | Obtains the number of removals from this buffer.| 613| getMatchCount(): number | Obtains the number of times that the queried values are matched.| 614| getPutCount(): number | Obtains the number of additions to this buffer.| 615| isEmpty(): boolean | Checks whether this buffer is empty. This API returns **true** if the buffer does not contain any value.| 616| get(key: K) : V \| undefined | Obtains the value of the specified key. This API returns the value of the key if a match is found in the buffer; otherwise, it returns **undefined**.| 617| put(key: K , value: V): V | Adds a key-value pair to the buffer and outputs the value associated with the key. This API returns the existing value if the key already exists; otherwise, it returns the value added. If the key or value is null, an exception will be thrown.| 618| keys(): K[ ] | Obtains all keys in this buffer, listed from the most to the least recently used.| 619| remove(key: K): V \| undefined | Removes the specified key and its value from this buffer.| 620| afterRemoval(isEvict: boolean, key: K, value : V, newValue : V):void | Performs subsequent operations after a value is removed.| 621| contains(key: K): boolean | Checks whether this buffer contains the specified key. This API returns **true** if the buffer contains the specified key.| 622| createDefault(key: K): V | Creates a value if the value of the specified key is not available.| 623| entries(): [K,V] | Obtains a new iterator object that contains all key-value pairs in this buffer. The key and value of each pair are objects.| 624| \[Symbol.iterator\](): [K,V] | Obtains a two-dimensional array in key-value pairs.| 625| constructor(lowerObj: ScopeType, upperObj : ScopeType) | A constructor used to create a **Scope** object with the specified upper and lower limits.| 626| toString(): string | Obtains a string representation that contains this **Scope**.| 627| intersect(range: Scope): Scope | Obtains the intersection of this **Scope** and the given **Scope**.| 628| intersect(lowerObj: ScopeType, upperObj: ScopeType): Scope | Obtains the intersection of this **Scope** and the given lower and upper limits.| 629| getUpper(): ScopeType | Obtains the upper limit of this **Scope**.| 630| getLower(): ScopeType | Obtains the lower limit of this **Scope**.| 631| expand(lowerObj: ScopeType, upperObj: ScopeType): Scope | Obtains the union set of this **Scope** and the given lower and upper limits.| 632| expand(range: Scope): Scope | Obtains the union set of this **Scope** and the given **Scope**.| 633| expand(value: ScopeType): Scope | Obtains the union set of this **Scope** and the given value.| 634| contains(value: ScopeType): boolean | Checks whether a value is within this **Scope**.| 635| contains(range: Scope): boolean | Checks whether a range is within this **Scope**.| 636| clamp(value: ScopeType): ScopeType | Limits a value to this **Scope**.| 637| function printf(format: string, ...args: Object[]): string | Prints the input content in a formatted string. **format** can contain zero or more format specifiers.| 638| function getErrorString(errno: number): string | Obtains detailed information about a system error code.| 639| function callbackWrapper(original: Function): (err: Object, value: Object) => void | Wraps an asynchronous function (or a function that returns a promise) into an error-first callback, which means that **(err, value) => ...** is used as the last parameter of the callback. In the callback, the first parameter indicates the cause of the rejection (the value is **null** if the promise has been resolved), and the second parameter indicates the resolved value.| 640| function promiseWrapper(original: (err: Object, value: Object) => void): Object | Wraps a function that follows the error-first callback paradigm into a promise.| 641| isAnyArrayBuffer(value: Object): boolean | Checks whether the input value is of the **ArrayBuffer** or **SharedArrayBuffer** type.| 642| isArrayBufferView(value: Object): boolean | Checks whether the input value is of the **ArrayBufferView** type, which is a helper type representing any of the following: napi_int8_array, napi_uint8_array, napi_uint8_clamped_array, napi_int16_array, napi_uint16_array, napi_int32_array, napi_uint32_array, napi_float32_array, napi_float64_array, and DataView.| 643| isArgumentsObject(value: Object): boolean | Checks whether the input value is of the **arguments** type.| 644| isArrayBuffer(value: Object): boolean | Checks whether the input value is of the **ArrayBuffer** type.| 645| isAsyncFunction(value: Object): boolean | Checks whether the input value is an asynchronous function.| 646| isBigInt64Array(value: Object): boolean | Checks whether the input value is of the **BigInt64Array** type.| 647| isBigUint64Array(value: Object): boolean | Checks whether the input value is of the **BigUint64Array** type.| 648| isBooleanObject(value: Object): boolean | Checks whether the input value is of the **Boolean** type.| 649| isBoxedPrimitive(value: Object): boolean | Checks whether the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type.| 650| isDataView(value: Object): boolean | Checks whether the input value is of the **DataView** type.| 651| isDate(value: Object): boolean | Checks whether the input value is of the **Date** type.| 652| isExternal(value: Object): boolean | Checks whether the input value is of the **native external** type.| 653| isFloat32Array(value: Object): boolean | Checks whether the input value is of the **Float32Array** type.| 654| isFloat64Array(value: Object): boolean | Checks whether the input value is of the **Float64Array** type.| 655| isGeneratorFunction(value: Object): boolean | Checks whether the input value is a generator function.| 656| isGeneratorObject(value: Object): boolean | Checks whether the input value is a generator object.| 657| isInt8Array(value: Object): boolean | Checks whether the input value is of the **Int8Array** type.| 658| isInt16Array(value: Object): boolean | Checks whether the input value is of the **Int16Array** type.| 659| isInt32Array(value: Object): boolean | Checks whether the input value is of the **Int32Array** type.| 660| isMap(value: Object): boolean | Checks whether the input value is of the **Map** type.| 661| isMapIterator(value: Object): boolean | Checks whether the input value is of the **MapIterator** type.| 662| isModuleNamespaceObject(value: Object): boolean | Checks whether the input value is a module namespace object.| 663| isNativeError(value: Object): boolean | Checks whether the input value is of the **Error** type.| 664| isNumberObject(value: Object): boolean | Checks whether the input value is a number object.| 665| isPromise(value: Object): boolean | Checks whether the input value is a promise.| 666| isProxy(value: Object): boolean | Checks whether the input value is a proxy.| 667| isRegExp(value: Object): boolean | Checks whether the input value is a regular expression.| 668| isSet(value: Object): boolean | Checks whether the input value is of the **Set** type.| 669| isSetIterator(value: Object): boolean | Checks whether the input value is of the **SetIterator** type.| 670| isSharedArrayBuffer(value: Object): boolean | Checks whether the input value is of the **SharedArrayBuffer** type.| 671| isStringObject(value: Object): boolean | Checks whether the input value is a string object.| 672| isSymbolObject(value: Object): boolean | Checks whether the input value is a symbol object.| 673| isTypedArray(value: Object): boolean | Checks whether the input value is of the **TypedArray** type.| 674| isUint8Array(value: Object): boolean | Checks whether the input value is of the **Uint8Array** type.| 675| isUint8ClampedArray(value: Object): boolean | Checks whether the input value is of the **Uint8ClampedArray** type.| 676| isUint16Array(value: Object): boolean | Checks whether the input value is of the **Uint16Array** type.| 677| isUint32Array(value: Object): boolean | Checks whether the input value is of the **Uint32Array** type.| 678| isWeakMap(value: Object): boolean | Checks whether the input value is of the **WeakMap** type.| 679| isWeakSet(value: Object): boolean | Checks whether the input value is of the **WeakSet** type.| 680 681Each format specifier in **printf()** is replaced with the converted value of the corresponding parameter. The following format specifiers are supported: 682| Format Specifier| Description| 683| -------- | -------- | 684| %s: | String. It is used to convert all values except **BigInt**, **Object**, and **-0**.| 685| %d: | Number. It is used to convert all values except **BigInt** and **Symbol**.| 686| %i: | **parseInt(value, 10)**. It used to convert all values except **BigInt** and **Symbol**.| 687| %f: | **parseFloat(value)**. It is used to convert all values except **Symbol**.| 688| %j: | JSON. A circular reference in the parameter will be replaced with the string **'[Circular]'**.| 689| %o: | A common JavaScript object represented in a string. It is similar to **util.inspect()** with the option **{ showHidden: true, showProxy: true }**. This will display a complete object, including innumerable properties and proxies.| 690| %O: | Object. A string representation of an object with a common JavaScript object format. It is similar to **util.inspect()** without options. This will display a complete object, excluding innumerable properties and proxies.| 691| %c: | This specifier is ignored and will jump any incoming CSS.| 692| %%: | Single percent sign ('%'). This does not consume to-be-sampled parameters.| 693 694#### How to Use 695Use the APIs as follows: 696 6971. readonly encoding() 698 699``` 700import util from '@ohos.util' 701var textEncoder = new util.TextEncoder(); 702var getEncoding = textEncoder.encoding(); 703``` 7042. encode() 705``` 706import util from '@ohos.util' 707var textEncoder = new util.TextEncoder(); 708var result = textEncoder.encode('abc'); 709``` 7103. encodeInto() 711``` 712import util from '@ohos.util' 713var textEncoder = new util.TextEncoder(); 714var obj = textEncoder.encodeInto('abc', dest); 715``` 7164. textDecoder() 717``` 718import util from '@ohos.util' 719var textDecoder = new util.textDecoder("utf-16be", {fatal : true, ignoreBOM : false}); 720``` 7215. readonly encoding() 722``` 723import util from '@ohos.util' 724var textDecoder = new util.textDecoder("utf-16be", {fatal : true, ignoreBOM : false}); 725var getEncoding = textDecoder.encoding(); 726``` 7276. readonly fatal() 728``` 729import util from '@ohos.util' 730var textDecoder = new util.textDecoder("utf-16be", {fatal : true, ignoreBOM : false}); 731var fatalStr = textDecoder.fatal(); 732``` 7337. readonly ignoreBOM() 734``` 735import util from '@ohos.util' 736var textDecoder = new util.textDecoder("utf-16be", {fatal : true, ignoreBOM : false}); 737var ignoreBom = textDecoder.ignoreBOM(); 738``` 7398. decode() 740``` 741import util from '@ohos.util' 742var textDecoder = new util.textDecoder("utf-16be", {fatal : true, ignoreBOM : false}); 743var result = textDecoder.decode(input, {stream : true}); 744``` 7459. decodeWithStream() 746``` 747import util from '@ohos.util' 748var textDecoder = new util.textDecoder("utf-16be", {fatal : true, ignoreBOM : false}); 749var result = textDecoder.decodeWithStream(input, {stream : true}); 750``` 75110. printf() 752``` 753import util from '@ohos.util' 754var format = "%%%o%%%i%s"; 755var value = function aa(){}; 756var value1 = 1.5; 757var value2 = "qwer"; 758var result = util.printf(format,value,value1,value2); 759``` 76011. getErrorString() 761``` 762import util from '@ohos.util' 763var errnum = 13; 764var result = util.getErrorString(errnum); 765``` 76612. callbackWrapper() 767``` 768import util from '@ohos.util' 769async function promiseFn() { 770 return Promise.resolve('value'); 771}; 772var cb = util.callbackWrapper(promiseFn); 773cb((err, ret) => { 774 expect(err).strictEqual(null); 775 expect(ret).strictEqual('value'); 776}) 777``` 77813. promiseWrapper() 779``` 780import util from '@ohos.util' 781function aysnFun(str1, str2, callback) { 782 if (typeof str1 === 'string' && typeof str1 === 'string') { 783 callback(null, str1 + str2); 784 } else { 785 callback('type err'); 786 } 787} 788let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); 789newPromiseObj.then(res => { 790 expect(res).strictEqual('HelloWorld'); 791}) 792``` 79314. encodeSync() 794``` 795import util from '@ohos.util' 796var that = new util.Base64(); 797var array = new Uint8Array([115,49,51]); 798var result = that.encodeSync(array); 799``` 80015. encodeToStringSync() 801``` 802import util from '@ohos.util' 803var that = new util.Base64(); 804var array = new Uint8Array([115,49,51]); 805var result = that.encodeToStringSync(array); 806``` 80716. decodeSync() 808``` 809import util from '@ohos.util' 810var that = new util.Base64() 811var buff = 'czEz'; 812var result = that.decodeSync(buff); 813 814``` 81517. encode() 816``` 817import util from '@ohos.util' 818var that = new util.Base64() 819var array = new Uint8Array([115,49,51]); 820await that.encode(array).then(val=>{ 821}) 822done() 823``` 82418. encodeToString() 825``` 826import util from '@ohos.util' 827var that = new util.Base64() 828var array = new Uint8Array([115,49,51]); 829await that.encodeToString(array).then(val=>{ 830}) 831done() 832``` 83319. decode() 834``` 835import util from '@ohos.util' 836var that = new util.Base64() 837var buff = 'czEz'; 838await that.decode(buff).then(val=>{ 839}) 840done() 841``` 84220. createRationalFromString() 843``` 844import util from '@ohos.util' 845var pro = new util.RationalNumber(0, 0); 846var res = pro.createRationalFromString("-1:2"); 847var result1 = res.valueOf(); 848``` 84921. compareTo() 850``` 851import util from '@ohos.util' 852var pro = new util.RationalNumber(2, 1); 853var proc = new util.RationalNumber(3, 4); 854var res = pro.compareTo(proc); 855``` 85622. equals() 857``` 858import util from '@ohos.util' 859var pro = new util.RationalNumber(2, 1); 860var proc = new util.RationalNumber(3, 4); 861var res = pro.equals(proc); 862``` 86323. valueOf() 864``` 865import util from '@ohos.util' 866var pro = new util.RationalNumber(2, 1); 867var res = pro.valueOf(); 868``` 86924. getCommonDivisor() 870``` 871import util from '@ohos.util' 872var pro = new util.RationalNumber(0, 0); 873var res = pro.getCommonDivisor(4, 8); 874``` 87525. getDenominator() 876``` 877import util from '@ohos.util' 878var pro = new util.RationalNumber(2, 1); 879var res = pro.getDenominator(); 880``` 88126. getNumerator() 882``` 883import util from '@ohos.util' 884var pro = new util.RationalNumber(-2, 1); 885var res = pro.getNumerator(); 886``` 88727. isFinite() 888``` 889import util from '@ohos.util' 890var pro = new util.RationalNumber(-2, 1); 891var res = pro.isFinite(); 892``` 89328. isNaN() 894``` 895import util from '@ohos.util' 896var pro = new util.RationalNumber(-2, 1); 897var res = pro.isNaN(); 898``` 89929. isZero() 900``` 901import util from '@ohos.util' 902var pro = new util.RationalNumber(-2, 1); 903var res = pro.isZero(); 904``` 90530. toString() 906``` 907import util from '@ohos.util' 908var pro = new util.RationalNumber(-2, 1); 909var res = pro.toString(); 910``` 91131. updateCapacity() 912``` 913import util from '@ohos.util' 914var pro = new util.LruBuffer(); 915var result = pro.updateCapacity(100); 916``` 91732. toString() 918``` 919import util from '@ohos.util' 920var pro = new util.LruBuffer(); 921pro.put(2,10); 922pro.get(2); 923pro.remove(20); 924var result = pro.toString(); 925``` 92633. values() 927``` 928import util from '@ohos.util' 929var pro = new util.LruBuffer(); 930pro.put(2,10); 931pro.put(2,"anhu"); 932pro.put("afaf","grfb"); 933var result = pro.values(); 934``` 93534. length 936``` 937import util from '@ohos.util' 938var pro = new util.LruBuffer(); 939pro.put(2,10); 940pro.put(1,8); 941var result = pro.length; 942``` 94335. getCapacity() 944``` 945import util from '@ohos.util' 946var pro = new util.LruBuffer(); 947var result = pro.getCapacity(); 948``` 94936. clear() 950``` 951import util from '@ohos.util' 952var pro = new util.LruBuffer(); 953pro.put(2,10); 954pro.clear(); 955``` 95637. getCreateCount() 957``` 958import util from '@ohos.util' 959var pro = new util.LruBuffer(); 960pro.put(1,8); 961var result = pro.getCreateCount(); 962``` 96338. getMissCount() 964``` 965import util from '@ohos.util' 966var pro = new util.LruBuffer(); 967pro.put(2,10); 968pro.get(2) 969var result = pro.getMissCount(); 970``` 97139. getRemovalCount() 972``` 973 974import util from '@ohos.util' 975var pro = new util.LruBuffer(); 976pro.put(2,10); 977pro.updateCapacity(2); 978pro.put(50,22); 979var result = pro.getRemovalCount(); 980 981``` 98240. getMatchCount() 983``` 984import util from '@ohos.util' 985var pro = new util.LruBuffer(); 986pro.put(2,10); 987pro.get(2); 988var result = pro.getMatchCount(); 989``` 99041. getPutCount() 991``` 992import util from '@ohos.util' 993var pro = new util.LruBuffer(); 994pro.put(2,10); 995var result = pro.getPutCount(); 996``` 99742. isEmpty() 998``` 999import util from '@ohos.util' 1000var pro = new util.LruBuffer(); 1001pro.put(2,10); 1002var result = pro.isEmpty(); 1003``` 100443. get() 1005 1006``` 1007import util from '@ohos.util' 1008var pro = new util.LruBuffer(); 1009pro.put(2,10); 1010var result = pro.get(2); 1011``` 101244. put() 1013``` 1014import util from '@ohos.util' 1015var pro = new util.LruBuffer(); 1016var result = pro.put(2,10); 1017``` 101845. keys() 1019``` 1020import util from '@ohos.util' 1021var pro = new util.LruBuffer(); 1022pro.put(2,10); 1023var result = pro.keys(); 1024``` 102546. remove() 1026``` 1027import util from '@ohos.util' 1028var pro = new util.LruBuffer(); 1029pro.put(2,10); 1030var result = pro.remove(20); 1031``` 103247. contains() 1033``` 1034import util from '@ohos.util' 1035var pro = new util.LruBuffer(); 1036pro.put(2,10); 1037var result = pro.contains(20); 1038``` 103948. createDefault() 1040``` 1041import util from '@ohos.util' 1042var pro = new util.LruBuffer(); 1043var result = pro.createDefault(50); 1044``` 104549. entries() 1046``` 1047import util from '@ohos.util' 1048var pro = new util.LruBuffer(); 1049pro.put(2,10); 1050var result = pro.entries(); 1051``` 105250. \[Symbol.iterator\]() 1053``` 1054import util from '@ohos.util' 1055var pro = new util.LruBuffer(); 1056pro .put(2,10); 1057var result = pro[symbol.iterator](); 1058``` 105951. afterRemoval() 1060``` 1061import util from '@ohos.util' 1062var arr = [ ]; 1063class ChildLruBuffer extends util.LruBuffer 1064{ 1065 constructor() 1066 { 1067 super(); 1068 } 1069 static getInstance() 1070 { 1071 if(this.instance == null) 1072 { 1073 this.instance = new ChildLruBuffer(); 1074 } 1075 return this.instance; 1076 } 1077 afterRemoval(isEvict, key, value, newValue) 1078 { 1079 if (isEvict === false) 1080 { 1081 arr = [key, value, newValue]; 1082 } 1083 } 1084} 1085ChildLruBuffer.getInstance().afterRemoval(false,10,30,null) 1086``` 1087A new constructor of **Scope** to implement the **compareTo** method. 1088 1089``` 1090class Temperature { 1091 constructor(value) { 1092 this._temp = value; 1093 } 1094 compareTo(value) { 1095 return this._temp >= value.getTemp(); 1096 } 1097 getTemp() { 1098 return this._temp; 1099 } 1100 toString() { 1101 return this._temp.toString(); 1102 } 1103} 1104``` 1105 110652. constructor() 1107 1108``` 1109var tempLower = new Temperature(30); 1110var tempUpper = new Temperature(40); 1111var range = new Scope(tempLower, tempUpper); 1112``` 1113 111453. toString() 1115 1116``` 1117var tempLower = new Temperature(30); 1118var tempUpper = new Temperature(40); 1119var range = new Scope(tempLower, tempUpper); 1120var result = range.toString() // => [30,40] 1121``` 1122 112354. intersect() 1124 1125``` 1126var tempLower = new Temperature(30); 1127var tempUpper = new Temperature(40); 1128var range = new Scope(tempLower, tempUpper); 1129var tempMiDF = new Temperature(35); 1130var tempMidS = new Temperature(39); 1131var rangeFir = new Scope(tempMiDF, tempMidS); 1132var result = range.intersect(rangeFir) // => [35,39] 1133``` 1134 113555. intersect() 1136 1137``` 1138var tempLower = new Temperature(30); 1139var tempUpper = new Temperature(40); 1140var tempMiDF = new Temperature(35); 1141var tempMidS = new Temperature(39); 1142var range = new Scope(tempLower, tempUpper); 1143var result = range.intersect(tempMiDF, tempMidS) // => [35,39] 1144``` 1145 114656. getUpper() 1147 1148``` 1149var tempLower = new Temperature(30); 1150var tempUpper = new Temperature(40); 1151var range = new Scope(tempLower, tempUpper); 1152var result = range.getUpper() // => 40 1153``` 1154 115557. getLower() 1156 1157``` 1158var tempLower = new Temperature(30); 1159var tempUpper = new Temperature(40); 1160var range = new Scope(tempLower, tempUpper); 1161var result = range.getLower() // => 30 1162``` 1163 116458. expand() 1165 1166``` 1167var tempLower = new Temperature(30); 1168var tempUpper = new Temperature(40); 1169var tempMiDF = new Temperature(35); 1170var tempMidS = new Temperature(39); 1171var range = new Scope(tempLower, tempUpper); 1172var result = range.expand(tempMiDF, tempMidS) // => [30,40] 1173``` 1174 117559. expand() 1176 1177``` 1178var tempLower = new Temperature(30); 1179var tempUpper = new Temperature(40); 1180var tempMiDF = new Temperature(35); 1181var tempMidS = new Temperature(39); 1182var range = new Scope(tempLower, tempUpper); 1183var rangeFir = new Scope(tempMiDF, tempMidS); 1184var result = range.expand(rangeFir) // => [30,40] 1185``` 1186 118760. expand() 1188 1189``` 1190var tempLower = new Temperature(30); 1191var tempUpper = new Temperature(40); 1192var tempMiDF = new Temperature(35); 1193var range = new Scope(tempLower, tempUpper); 1194var result = range.expand(tempMiDF) // => [30,40] 1195``` 1196 119761. contains() 1198 1199``` 1200var tempLower = new Temperature(30); 1201var tempUpper = new Temperature(40); 1202var tempMiDF = new Temperature(35); 1203var range = new Scope(tempLower, tempUpper); 1204var result = range.contains(tempMiDF) // => true 1205``` 1206 120762. contains() 1208 1209``` 1210var tempLower = new Temperature(30); 1211var tempUpper = new Temperature(40); 1212var range = new Scope(tempLower, tempUpper); 1213var tempLess = new Temperature(20); 1214var tempMore = new Temperature(45); 1215var rangeSec = new Scope(tempLess, tempMore); 1216var result = range.contains(rangeSec) // => true 1217``` 1218 121963. clamp() 1220 1221``` 1222var tempLower = new Temperature(30); 1223var tempUpper = new Temperature(40); 1224var tempMiDF = new Temperature(35); 1225var range = new Scope(tempLower, tempUpper); 1226var result = range.clamp(tempMiDF) // => 35 1227``` 122864. isAnyArrayBuffer() 1229``` 1230import util from '@ohos.util' 1231var proc = new util.Types(); 1232var result = proc.isAnyArrayBuffer(new ArrayBuffer([])) 1233``` 123465. isArrayBufferView() 1235``` 1236import util from '@ohos.util' 1237var proc = new util.Types(); 1238var result = proc.isArrayBufferView(new DataView(new ArrayBuffer(16))); 1239``` 124066. isArgumentsObject() 1241``` 1242import util from '@ohos.util' 1243function foo() { 1244 var result = proc.isArgumentsObject(arguments); 1245 } 1246var f = foo(); 1247``` 124867. isArrayBuffer() 1249``` 1250import util from '@ohos.util' 1251var proc = new util.Types(); 1252var result = proc.isArrayBuffer(new ArrayBuffer([])); 1253``` 125468. isAsyncFunction() 1255``` 1256import util from '@ohos.util' 1257var proc = new util.Types(); 1258var result = proc.isAsyncFunction(async function foo() {}); 1259``` 126069. isBigInt64Array() 1261``` 1262import util from '@ohos.util' 1263var proc = new util.Types(); 1264var result = proc.isBigInt64Array(new Int16Array([])); 1265``` 126670. isBigUint64Array() 1267``` 1268import util from '@ohos.util' 1269var proc = new util.Types(); 1270var result = proc.isBigUint64Array(new Int16Array([])); 1271``` 127271. isBooleanObject() 1273``` 1274import util from '@ohos.util' 1275var proc = new util.Types(); 1276var result = proc.isBooleanObject(new Boolean(false)); 1277``` 127872. isBoxedPrimitive() 1279``` 1280import util from '@ohos.util' 1281var proc = new util.Types(); 1282var result = proc.isBoxedPrimitive(new Boolean(false)); 1283``` 128473. isDataView() 1285``` 1286import util from '@ohos.util' 1287var proc = new util.Types(); 1288const ab = new ArrayBuffer(20); 1289var result = proc.isDataView(new DataView(ab)); 1290``` 129174. isDate() 1292``` 1293import util from '@ohos.util' 1294var proc = new util.Types(); 1295var result = proc.isDate(new Date()); 1296``` 129775. isExternal() 1298``` 1299import util from '@ohos.util' 1300const data = util.createExternalType(); 1301var reult13 = proc.isExternal(data); 1302``` 130376. isFloat32Array() 1304``` 1305import util from '@ohos.util' 1306var proc = new util.Types(); 1307var result = proc.isFloat32Array(new Float32Array([])); 1308``` 130977. isFloat64Array() 1310``` 1311import util from '@ohos.util' 1312var proc = new util.Types(); 1313var result = proc.isFloat64Array(new Float64Array([])); 1314``` 131578. isGeneratorFunction() 1316``` 1317import util from '@ohos.util' 1318var proc = new util.Types(); 1319var result = proc.isGeneratorFunction(function* foo() {}); 1320``` 132179. isGeneratorObject() 1322``` 1323import util from '@ohos.util' 1324var proc = new util.Types(); 1325function* foo() {} 1326const generator = foo(); 1327var result = proc.isGeneratorObject(generator); 1328``` 132980. isInt8Array() 1330``` 1331import util from '@ohos.util' 1332var proc = new util.Types(); 1333var result = proc.isInt8Array(new Int8Array([])); 1334``` 133581. isInt16Array() 1336``` 1337import util from '@ohos.util' 1338var proc = new util.Types(); 1339var result = proc.isInt16Array(new Int16Array([])); 1340``` 134182. isInt32Array() 1342``` 1343import util from '@ohos.util' 1344var proc = new util.Types(); 1345var result = proc.isInt32Array(new Int32Array([])); 1346``` 134783. isMap() 1348``` 1349import util from '@ohos.util' 1350var proc = new util.Types(); 1351var result = proc.isMap(new Map()); 1352``` 135384. isMapIterator() 1354``` 1355import util from '@ohos.util' 1356var proc = new util.Types(); 1357var result = proc.isMapIterator(map.keys()); 1358``` 135985. isModuleNamespaceObject() 1360``` 1361import util from '@ohos.util' 1362var proc = new util.Types(); 1363var result = proc.isModuleNamespaceObject(util); 1364``` 136586. isNativeError() 1366``` 1367import util from '@ohos.util' 1368var proc = new util.Types(); 1369var result = proc.isNativeError(new TypeError()); 1370``` 137187. isNumberObject() 1372``` 1373import util from '@ohos.util' 1374var proc = new util.Types(); 1375var result = proc.isNumberObject(new Number(0)); 1376``` 137788. isPromise() 1378``` 1379import util from '@ohos.util' 1380var proc = new util.Types(); 1381var result = proc.isPromise(Promise.resolve(42)); 1382``` 138389. isProxy() 1384``` 1385import util from '@ohos.util' 1386var proc = new util.Types(); 1387const target = {}; 1388const proxy = new Proxy(target, {}); 1389var result = proc.isProxy(proxy); 1390``` 139190. isRegExp() 1392``` 1393import util from '@ohos.util' 1394var proc = new util.Types(); 1395var result = proc.isRegExp(new RegExp('abc')); 1396``` 139791. isSet() 1398``` 1399import util from '@ohos.util' 1400var proc = new util.Types(); 1401var result = proc.isSet(new Set()); 1402``` 140392. isSetIterator() 1404``` 1405import util from '@ohos.util' 1406var proc = new util.Types(); 1407const set = new Set(); 1408var result = proc.isSetIterator(set.keys()); 1409``` 141093. isSharedArrayBuffer() 1411``` 1412import util from '@ohos.util' 1413var proc = new util.Types(); 1414var result = proc.isSharedArrayBuffer(new ArrayBuffer([])); 1415``` 141694. isStringObject() 1417``` 1418import util from '@ohos.util' 1419var proc = new util.Types(); 1420var result = proc.isStringObject(new String('foo')); 1421``` 142295. isSymbolObject() 1423``` 1424import util from '@ohos.util' 1425var proc = new util.Types(); 1426const symbols = Symbol('foo'); 1427var result = proc.isSymbolObject(Object(symbols)); 1428``` 142996. isTypedArray() 1430``` 1431import util from '@ohos.util' 1432var proc = new util.Types(); 1433var result = proc.isTypedArray(new Float64Array([])); 1434``` 143597. isUint8Array() 1436``` 1437import util from '@ohos.util' 1438var proc = new util.Types(); 1439var result = proc.isUint8Array(new Uint8Array([])); 1440``` 144198. isUint8ClampedArray() 1442``` 1443import util from '@ohos.util' 1444var proc = new util.Types(); 1445var result = proc.isUint8ClampedArray(new Uint8ClampedArray([])); 1446``` 144799. isUint16Array() 1448``` 1449import util from '@ohos.util' 1450var proc = new util.Types(); 1451var result = proc.isUint16Array(new Uint16Array([])); 1452``` 1453100. isUint32Array() 1454``` 1455import util from '@ohos.util' 1456var proc = new util.Types(); 1457var result = proc.isUint32Array(new Uint32Array([])); 1458``` 1459101. isWeakMap() 1460``` 1461import util from '@ohos.util' 1462var proc = new util.Types(); 1463var result = proc.isWeakMap(new WeakMap()); 1464``` 1465102. isWeakSet() 1466``` 1467import util from '@ohos.util' 1468var proc = new util.Types(); 1469var result = proc.isWeakSet(new WeakSet()); 1470``` 1471 1472## js_sys_module 1473### Introduction 1474js_sys_module provides the following classes:<br>**Process**: provides APIs to obtain multiple IDs of a process, obtain and modify the working directory of a process, and exit and stop a process. **childprocess**: provides APIs for a process to obtain the standard input and output of its child processes, send signals, and close its child processes. 1475### Directory Structure 1476 1477``` 1478commonlibrary/ets_utils/js_sys_module/ 1479├── Class:PROCESS # Process class 1480├── Uid # UID attribute 1481├── Gid # GID attribute 1482├── EUid # EUID attribute 1483├── EGid # EGID attribute 1484├── Groups # Groups attribute 1485├── Pid # PID attribute 1486├── Ppid # PPID attribute 1487├── chdir() # chdir method 1488├── uptime() # uptime method 1489├── kill() # kill method 1490├── abort() # abort method 1491├── on() # on method 1492├── tid # tid method 1493├── getStartRealtime() # getStartRealtime method 1494├── getAvailableCores() # getAvailableCores method 1495├── getPastCputime() # getPastCputime method 1496├── isIsolatedProcess() # isIsolatedProcess method 1497├── is64Bit() # is64Bit method 1498├── isAppUid() # isAppUid method 1499├── getUidForName() # getUidForName method 1500├── getThreadPriority() # getThreadPriority method 1501├── getSystemConfig() # getSystemConfig method 1502├── getEnvironmentVar() # getEnvironmentVar method 1503├── exit() # exit method 1504├── cwd() # cwd method 1505├── off() # off method 1506├── runCmd() # runCmd method 1507└─── Class:CHILDPROCESS # ChildProcess class 1508 ├── close() # close method 1509 ├── kill() # kill method 1510 ├── getOutput() # getOutput method 1511 ├── getErrorOutput() # getErrorOutput method 1512 ├── wait() # wait method 1513 ├── killed # killed attribute 1514 ├── pid # PID attribute 1515 ├── ppid # PPID attribute 1516 └── exitCode # exitCode attribute 1517|—— Class:CONSOLE 1518 ├── debug() # debug method 1519 ├── log() # log method 1520 ├── info() # info method 1521 ├── warn() # warn method 1522 ├── error() # error method 1523 ├── assert() # assert method 1524 ├── count() # count method 1525 ├── countReset() # countReset method 1526 ├── dir() # dir method 1527 ├── dirxml() # dirxml method 1528 ├── group() # group method 1529 ├── groupCollapsed() # groupCollapsed method 1530 ├── groupEnd() # groupEnd method 1531 ├── table() # table method 1532 ├── time() # time method 1533 ├── timeEnd() # timeEnd method 1534 ├── timeLog() # timeLog method 1535 ├── trace() # trace method 1536|—— Class:TIMER 1537 ├── setInterval() # setInterval method 1538 ├── setTimeout() # setTimeout method 1539 ├── clearInterval() # clearInterval method 1540 ├── clearTimeout() # clearTimeout method 1541``` 1542 1543### How to Use 1544 1545#### Available APIs 1546| API| Description| 1547| -------- | -------- | 1548| const uid :number | Obtains the user identifier (UID) of this process.| 1549| const gid :number | Obtains the group identifier (GID) of this process.| 1550| const euid :number | Obtains the effective user identifier (EUID) of this process.| 1551| const egid :number | Obtains the effective group identifier (EGID) of this process.| 1552| const groups :number[] | Obtains an array with supplementary group IDs.| 1553| const pid :number | Obtains the process ID (PID) of this process.| 1554| const ppid :number | Obtains the parent process ID (PPID) of this process.| 1555| chdir(dir:string) :void | Changes the working directory of this process.| 1556| uptime() :number | Obtains the running time of this process, in seconds.| 1557| Kill(pid:number, signal:number) :boolean | Sends a signal to the specified process to terminate it. The value **true** means that the signal is sent.| 1558| abort() :void | Aborts a process and generates a core file. It will cause the process to exit immediately.| 1559| on(type:string ,listener:EventListener) :void | Stores the events triggered by the user.| 1560| exit(code:number):void | Terminates this process.| 1561| cwd():string | Obtains the working directory of this process.| 1562| off(type: string): boolean | Deletes the event stored by the user. The value **true** means that the event is deleted.| 1563| runCmd(command: string, options?: { timeout : number, killSignal : number \| string, maxBuffer : number }): ChildProcess |Forks a new process to run a shell command and returns the **ChildProcess** object. **command** indicates the shell command to run, and **options** indicates certain running parameters, such as **timeout**, **killsignal**, and **maxbuffer**, of the child process. If **timeout** is set, the child process sends the **kill** signal after the specified timeout reaches. **maxbuffer** is used to limit the maximum size of **stdout** and **stderr** that can be received.| 1564| wait(): Promise\<number>| Waits until the child process ends. It uses a promise to return the exit code of the child process.| 1565| getOutput(): Promise\<Uint8Array> | Obtains the standard output of the child process.| 1566| getErrorOutput(): Promise\<Uint8Array> | Obtains the standard error output of the child process.| 1567| const tid:number | Obtains the TID of the process.| 1568| getStartRealtime() :number | Obtains the duration (in milliseconds) from the time the system starts to the time the process starts.| 1569| getAvailableCores() :number[] | Obtains the number of CPU cores available for the process on a multi-core device.| 1570| getPastCputime() :number | Obtains the CPU time (in milliseconds) from the time the process starts to the current time.| 1571| isIsolatedProcess(): boolean | Checks whether this process is isolated.| 1572| is64Bit(): boolean | Checks whether this process is running in a 64-bit environment.| 1573| isAppUid(v:number): boolean | Checks whether a UID belongs to the current app.| 1574| getUidForName(v:string): number | Obtains the process UID based on the process name.| 1575| getThreadPriority(v:number): number | Obtains the thread priority based on the TID.| 1576| getSystemConfig(name:number): number | Obtains the system configuration based on the configuration name.| 1577| getEnvironmentVar(name:string): string | Obtains the value of an environment variable.| 1578| close(): void | Closes the child process in running.| 1579| kill(signal: number \| string): void | Sends a signal to the specified child process to terminate it.| 1580| readonly killed: boolean | Specifies whether the signal is sent. The value **true** means that the signal is sent.| 1581| readonly exitCode: number | Indicates the exit code of the child process.| 1582| readonly pid: number | Indicates the PID of the child process.| 1583| readonly ppid: number | Indicates the PPID of the process.| 1584| debug(message: string, ...arguments: any[]): void | print debug information. | 1585| log(message: string, ...arguments: any[]): void | print log information. | 1586| info(message: string, ...arguments: any[]): void | print info information. | 1587| warn(message: string, ...arguments: any[]): void | print warn information. | 1588| error(message: string, ...arguments: any[]): void | print error information. | 1589| assert(value?: Object, ...arguments: Object[]): void | if value is false,print arguments information. | 1590| count(label?: string): void | Counts the label name. | 1591| countReset(label?: string): void | Clear the count of label names. | 1592| dir(dir?: Object): void | Print the object content. | 1593| dirxml(...arguments: Object[]): void | print log information. | 1594| group(...arguments: Object[]): void | Indent one group | 1595| groupCollapsed(...arguments: Object[]): void | Indent one group | 1596| groupEnd(): void | Unindent one group. | 1597| table(tableData?: Object): void | Print data in tabular form. | 1598| time(label?: string): void | Start the clock. | 1599| timeEnd(label?: string): void | End the timer. | 1600| timeLog(label?: string, ...arguments: Object[]): void | Print current timing. | 1601| trace(...arguments: Object[]): void | Print current stack. | 1602| setInterval(handler: Function \| string, delay: number, ...arguments: any[]): number | Timing to call callback function. | 1603| setTimeout(handler: Function \| string, delay?: number, ...arguments: any[]): number | Call the callback function when the timing ends. | 1604| clearInterval(intervalID?: number): void | Clear the timing callback. | 1605| clearTimeout(timeoutID?: number): void |Clear the timing callback. | 1606 1607#### How to Use 1608 1609Use the APIs as follows: 16101. uid() 1611``` 1612uid(){ 1613 var res = Process.uid; 1614} 1615``` 16162. gid() 1617``` 1618gid(){ 1619 var result = Process.gid; 1620} 1621``` 16223. euid() 1623``` 1624euid(){ 1625 var and = Process.euid; 1626} 1627``` 16284. egid() 1629``` 1630egid(){ 1631 var resb = Process.egid; 1632} 1633``` 16345. groups() 1635``` 1636groups(){ 1637 var answer = Process.groups; 1638} 1639``` 16406. pid() 1641``` 1642pid(){ 1643 var result = Process.pid; 1644} 1645``` 16467. ppid() 1647``` 1648ppid(){ 1649 var result = Process.ppid; 1650} 1651``` 16528. chdir() 1653``` 1654chdir(){ 1655 Process.chdir("123456"); 1656} 1657``` 16589. uptime() 1659``` 1660uptime(){ 1661 var num = Process.uptime(); 1662} 1663``` 166410. kill() 1665``` 1666kill(){ 1667 var ansu = Process.kill(5,23); 1668} 1669``` 167011. abort() 1671``` 1672abort(){ 1673 Process.abort(); 1674} 1675``` 167612. on() 1677``` 1678on(){ 1679 function add(num){ 1680 var value = num + 5; 1681 return value; 1682 } 1683 Process.on("add",add); 1684} 1685``` 168613. exit() 1687``` 1688exit(){ 1689 Process.exit(15); 1690} 1691``` 169214. Cwd() 1693``` 1694Cwd(){ 1695 var result = Process.cwd(); 1696} 1697``` 169815. off() 1699 1700``` 1701off(){ 1702 var result = Process.off("add"); 1703} 1704``` 170516. runCmd() 1706``` 1707runCmd(){ 1708 var child = process.runCmd('echo abc') 1709 // killSignal can be a number or string. 1710 var child = process.runCmd('echo abc;', {killSignal : 'SIGKILL'}); 1711 var child = process.runCmd('sleep 5; echo abc;', {timeout : 1, killSignal : 9, maxBuffer : 2}) 1712} 1713``` 171417. wait() 1715``` 1716wait() 1717{ 1718 var child = process.runCmd('ls') 1719 var status = child.wait(); 1720 status.then(val => { 1721 console.log(val); 1722 }) 1723} 1724``` 172518. getOutput() 1726``` 1727getOutput(){ 1728 var child = process.runCmd('echo bcd;'); 1729 var res = child.getOutput(); 1730 child.wait(); 1731 res.then(val => { 1732 console.log(val); 1733 }) 1734} 1735``` 173619. getErrorOutput() 1737``` 1738getErrorOutput(){ 1739 var child = process.runCmd('makdir 1.txt'); // execute an error command 1740 var res = child.getErrorOutput(); 1741 child.wait(); 1742 res.then(val => { 1743 console.log(val); 1744 }) 1745} 1746``` 174720. close() 1748``` 1749close(){ 1750 var child = process.runCmd('ls; sleep 5s;') 1751 var result = child.close() 1752} 1753``` 175421. kill() 1755``` 1756kill(){ 1757 var child = process.runCmd('ls; sleep 5s;') 1758 var result = child.kill('SIGHUP'); 1759 child.wait(); 1760 var temp = child.killed; 1761} 1762``` 176322. killed 1764``` 1765{ 1766 var child = process.runCmd('ls; sleep 5;') 1767 child.kill(3); 1768 var killed_ = child.killed; 1769 child.wait(); 1770} 1771``` 177223. exitCode 1773``` 1774{ 1775 var child = process.runCmd('ls; sleep 5;') 1776 child.kill(9); 1777 child.wait(); 1778 var exitCode_ = child.exitCode; 1779} 1780``` 178124. pid 1782``` 1783pid 1784{ 1785 var child = process.runCmd('ls; sleep 5;') 1786 var pid_ = child.pid; 1787 child.wait(); 1788} 1789``` 179025. ppid 1791``` 1792ppid 1793{ 1794 var child = process.runCmd('ls; sleep 5;') 1795 var ppid_ = child.ppid; 1796 child.wait(); 1797} 1798``` 179926. tid 1800``` 1801tid(){ 1802 var ansu = Process.tid; 1803} 1804``` 180527. isIsolatedProcess() 1806``` 1807isIsolatedProcess(){ 1808 var ansu = Process.isIsolatedProcess()(); 1809} 1810``` 181128. isAppUid() 1812``` 1813isAppUid(){ 1814 var ansu = Process.isAppUid(10000); 1815} 1816``` 181729. is64Bit() 1818``` 1819is64Bit(){ 1820 var ansu = Process.is64Bit(); 1821} 1822``` 182330. getUidForName() 1824``` 1825getUidForName(){ 1826 var buf = "root"; 1827 var ansu = Process.getUidForName(buf); 1828} 1829``` 183031. getEnvironmentVar() 1831``` 1832getEnvironmentVar(){ 1833 var ansu = Process.getEnvironmentVar('USER'); 1834} 1835``` 183632. getAvailableCores() 1837``` 1838getAvailableCores(){ 1839 var ansu = Process.getAvailableCores(); 1840} 1841``` 184233. getThreadPriority() 1843``` 1844getThreadPriority(){ 1845 var result = Process.getTid(); 1846 var ansu = getThreadPriority(result); 1847} 1848``` 184934. getStartRealtime() 1850``` 1851getStartRealtime(){ 1852 var ansu = Process.getStartRealtime(); 1853} 1854``` 185535. getPastCputime() 1856``` 1857getPastCputime(){ 1858 var ansu = Process.getPastCputime(); 1859} 1860``` 186136. getSystemConfig() 1862``` 1863getSystemConfig(){ 1864 var _SC_ARG_MAX = 0; 1865 var ansu = Process.getSystemConfig(_SC_ARG_MAX) 1866} 1867``` 186837.console.debug() 1869``` 1870console.debug("print debug log"); 1871} 1872``` 187338.console.log() 1874``` 1875console.debug("print log"); 1876} 1877``` 187839.console.info() 1879``` 1880console.debug("print info log"); 1881} 1882``` 188340.console.warn() 1884``` 1885console.debug("print warn log"); 1886} 1887``` 188841.console.error() 1889``` 1890console.debug("print error log"); 1891} 1892``` 189342.console.assert() 1894``` 1895for (let number = 2; number <= 5; number++) { 1896 console.assert(number % 2 === 0, "error"); 1897} 1898``` 189943.console.count() 1900``` 1901console.count("myObj"); 1902``` 190344.console.countReset() 1904``` 1905console.count("myObj"); 1906console.countReset("myObj"); 1907``` 190845.console.dir() 1909``` 1910function cat(name, age, score){ 1911 this.name = name; 1912 this.age = age; 1913 this.score = score; 1914} 1915var c = new cat("ohos", 2, [6,8,7]); 1916console.dir(c); 1917``` 191846.console.dirxml() 1919``` 1920console.xml("print log"); 1921``` 192247.console.group() 1923``` 1924console.group(); 1925``` 192648.console.groupCollapsed() 1927``` 1928console.groupCollapsed(); 1929``` 193049.console.groupEnd() 1931``` 1932console.groupEnd(); 1933``` 193450.console.table() 1935``` 1936var languages = { 1937 csharp: { name: "C#", paradigm: "undefined" }, 1938 fsharp: { name: "F#", paradigm: "functional" } 1939}; 1940console.table(languages); 1941``` 194251.console.time() 1943``` 1944console.time("timer1"); 1945``` 194652.console.timeEnd() 1947``` 1948console.time("timer1"); 1949console.timeEnd("timer1"); 1950``` 195153.console.timeLog() 1952``` 1953console.time("timer1"); 1954console.timeLog("timer1"); 1955``` 195654.console.trace() 1957``` 1958console.trace(); 1959``` 196055.setInterval() 1961``` 1962function callback() { 1963 console.log("setInterval"); 1964}; 1965setInterval(callback, 100); 1966``` 196755.setTimeout() 1968``` 1969function callback() { 1970 console.log("setTimeout"); 1971}; 1972setTimeout(callback, 100); 1973``` 197455.clearInterval() 1975``` 1976function callback() { 1977 console.log("clearInterval"); 1978}; 1979var myVar = setInterval(callback, 1000); 1980clearInterval(myVar); 1981``` 198256.clearTimeout() 1983``` 1984function callback() { 1985 console.log("clearTimeout"); 1986}; 1987var myVar = setTimeout(callback, 1000); 1988clearTimeout(myVar); 1989``` 1990 1991## js_concurrent_module 1992 1993### Introduction 1994 1995The js_concurrent_module provides the worker thread, which communicates with the host thread through **postMessage**. 1996 1997### Available APIs 1998For details about the API implementation, see js_worker_module/worker. 1999 2000#### Worker Object 2001 2002Object used by the host thread to communicate with the worker thread. 2003 2004##### APIs 2005 20061. 2007 2008- API 2009 2010|constructor(scriptURL:string, options?:WorkerOptions) | Constructor used to create a worker object.| 2011|---|---| 2012 2013- Example 2014 2015You can use any of the following methods to create a worker thread, depending on whether the **workers** directory that stores the **worker.ts** file is at the same level as the **pages** directory and whether the FA or stage model is in use: 2016 2017(1) In the FA model, the **workers** and **pages** directories are at the same level. 2018``` 2019import worker from "@ohos.worker"; 2020const workerInstance = new worker.Worker("workers/worker.js", {name:"first worker"}); 2021``` 2022(2) In the FA model, the **workers** and **pages** directories are at different levels. 2023``` 2024import worker from "@ohos.worker"; 2025const workerInstance = new worker.Worker("../workers/worker.js", {name:"first worker"}); 2026``` 2027(3) In the stage model, the **workers** and **pages** directories are at the same level. 2028``` 2029import worker from "@ohos.worker"; 2030const workerInstance = new worker.Worker('entry/ets/workers/worker.ts'); 2031``` 2032(4) In the stage model, the **workers** and **pages** directories are at different levels. 2033``` 2034import worker from "@ohos.worker"; 2035const workerInstance = new worker.Worker('entry/ets/pages/workers/worker.ts'); 2036``` 2037scriptURL in the stage model — Description of "entry/ets/workers/worker.ts". 2038- **entry**: value of the **name** attribute under **module** in the **module.json5** file. 2039- **ets**: programming language in use. 2040- **worker.ts**: file for the module. You can also use a **worker.js** file. 2041 2042Depending on whether the **workers** and **pages** directories are at the same level, you may need to configure the **buildOption** attribute in the **build-profile.json5** file. 2043 2044(1) If the **workers** and **pages** directories are at the same level, the configuration is optional. 2045 2046In the FA model: 2047``` 2048 "buildOption": { 2049 "sourceOption": { 2050 "workers": [ 2051 "./src/main/ets/MainAbility/workers/worker.js" 2052 ] 2053 } 2054 } 2055``` 2056In the stage model: 2057``` 2058 "buildOption": { 2059 "sourceOption": { 2060 "workers": [ 2061 "./src/main/ets/workers/worker.ts" 2062 ] 2063 } 2064 } 2065``` 2066(2) If the **workers** and **pages** directories are at different levels, the configuration is mandatory. 2067 2068In the FA model: 2069``` 2070 "buildOption": { 2071 "sourceOption": { 2072 "workers": [ 2073 "./src/main/ets/workers/worker.js" 2074 ] 2075 } 2076 } 2077``` 2078In the stage model (the following assumes that the **workers** directory is under the **pages** directory): 2079``` 2080 "buildOption": { 2081 "sourceOption": { 2082 "workers": [ 2083 "./src/main/ets/pages/workers/worker.ts" 2084 ] 2085 } 2086 } 2087``` 20882. 2089 2090- API 2091 2092| postMessage(message:Object, options?:PostMessageOptions) | Sends a message to the worker thread. | 2093|---|---| 2094| postMessage(message:Object, transfer:ArrayBuffer[]) | Sends a message to the worker thread. | 2095 2096- Examples 2097 2098``` 2099// Example 1 2100import worker from "@ohos.worker" 2101const worker = new worker.Worker("workers/worker.js"); 2102worker.postMessage("hello world"); 2103 2104// Example 2 2105import worker from "@ohos.worker" 2106const worker = new worker.Worker("workers/worker.js"); 2107var buffer = new ArrayBuffer(8); 2108worker.postMessage(buffer, [buffer]); 2109``` 2110 21113. 2112 2113- API 2114 2115| on(type:string, listener:EventListener) | Adds an event listener to the worker. | 2116|---|---| 2117 2118- Examples 2119 2120``` 2121import worker from "@ohos.worker" 2122const worker = new worker.Worker("workers/worker.js"); 2123worker.on("alert", (e)=>{ 2124 console.log("worker on..."); 2125}); 2126``` 2127 21284. 2129 2130- API 2131 2132| once(type:string, listener:EventListener) | Adds an event listener to the worker and removes the event listener automatically after it is invoked once. | 2133|---|---| 2134 2135- Examples 2136 2137``` 2138import worker from "@ohos.worker" 2139const worker = new worker.Worker("workers/worker.js"); 2140worker.once("alert", (e)=>{ 2141 console.log("worker once..."); 2142}); 2143``` 2144 21455. 2146 2147- API 2148 2149| off(type:string, listener?:EventListener) | Removes an event listener for the worker. | 2150|---|---| 2151 2152- Examples 2153 2154``` 2155import worker from "@ohos.worker" 2156const worker = new worker.Worker("workers/worker.js"); 2157worker.off("alert"); 2158``` 2159 21606. 2161 2162- API 2163 2164| terminate() | Terminates the worker thread to stop the worker from receiving messages. | 2165|---|---| 2166 2167- Example 2168 2169``` 2170import worker from "@ohos.worker" 2171const worker = new worker.Worker("workers/worker.js"); 2172worker.terminate(); 2173``` 2174 21757. 2176 2177- API 2178 2179| removeEventListener(type:string, listener?:EventListener) | Removes an event listener for the worker. | 2180|---|---| 2181 2182- Example 2183 2184``` 2185import worker from "@ohos.worker" 2186const worker = new worker.Worker("workers/worker.js"); 2187worker.removeEventListener("alert", (e)=>{ 2188 console.log("worker removeEventListener..."); 2189}); 2190``` 2191 21928. 2193 2194- API 2195 2196| dispatchEvent(event: Event) | Dispatches the event defined for the worker. | 2197|---|---| 2198 2199- Example 2200 2201``` 2202import worker from "@ohos.worker" 2203const worker = new worker.Worker("workers/worker.js"); 2204worker.dispatchEvent({type:"alert"}); 2205``` 2206 22079. 2208 2209- API 2210 2211| removeAllListener() | Removes all event listeners for the worker. | 2212|---|---| 2213 2214- Example 2215 2216``` 2217import worker from "@ohos.worker" 2218const worker = new worker.Worker("workers/worker.js"); 2219worker.removeAllListener(); 2220``` 2221 2222##### Attributes 2223 22241. 2225 2226- Attribute 2227 2228| onexit?:(code:number)=>void | Event handler to be called when the worker thread exits. The handler is executed in the host thread. | 2229|---|---| 2230 2231- Example 2232 2233``` 2234import worker from "@ohos.worker" 2235const worker = new worker.Worker("workers/worker.js"); 2236worker.onexit = function(e) { 2237 console.log("onexit..."); 2238} 2239``` 2240 22412. 2242 2243- Attribute 2244 2245| onerror?:(ev:ErrorEvent)=>void | Event handler to be called when an exception occurs during worker execution. The event handler is executed in the host thread. | 2246|---|---| 2247 2248- Example 2249 2250``` 2251import worker from "@ohos.worker" 2252const worker = new worker.Worker("workers/worker.js"); 2253worker.onerror = function(e) { 2254 console.log("onerror..."); 2255} 2256``` 2257 22583. 2259 2260- Attribute 2261 2262| onmessage?:(ev:MessageEvent)=>void | Event handler to be called when the host thread receives a message sent by the worker thread through **parentPort.postMessage**. The event handler is executed in the host thread.| 2263|---|---| 2264 2265- Example 2266 2267``` 2268import worker from "@ohos.worker" 2269const worker = new worker.Worker("workers/worker.js"); 2270worker.onmessage = function(e) { 2271 console.log("onmessage..."); 2272} 2273``` 2274 22754. 2276 2277- Attribute 2278 2279| onmessageerror?:(event:MessageEvent)=>void | Event handler to be called when the worker thread receives a message that cannot be serialized. The event handler is executed in the host thread.| 2280|---|---| 2281 2282- Example 2283 2284``` 2285import worker from "@ohos.worker" 2286const worker = new worker.Worker("workers/worker.js"); 2287worker.onmessageerror = function(e) { 2288 console.log("onmessageerror..."); 2289} 2290``` 2291 2292#### parentPort Object 2293 2294Object of the worker thread used to communicate with the host thread. 2295 2296##### APIs 2297 22981. 2299 2300- API 2301 2302| postMessage(message:Object, options?:PostMessageOptions) | Sends a message to the host thread from the worker thread.| 2303|---|---| 2304| postMessage(message:Object, transfer:ArrayBuffer[]) | Sends a message to the host thread from the worker thread. | 2305 2306- Example 2307 2308``` 2309// main.js 2310import worker from "@ohos.worker" 2311const worker = new worker.Worker("workers/worker.js"); 2312worker.postMessage("hello world"); 2313 2314// worker.js 2315import worker from "@ohos.worker" 2316const parentPort = worker.parentPort; 2317parentPort.onmessage = function(e) { 2318 parentPort.postMessage("hello world from worker.js"); 2319} 2320``` 2321 23222. 2323 2324- API 2325 2326| close() | Terminates the worker thread to stop the worker from receiving messages. | 2327|---|---| 2328 2329- Example 2330 2331``` 2332// main.js 2333import worker from "@ohos.worker" 2334const worker = new worker.Worker("workers/worker.js"); 2335worker.postMessage("hello world"); 2336 2337// worker.js 2338import worker from "@ohos.worker" 2339const parentPort = worker.parentPort; 2340parentPort.onmessage = function(e) { 2341 parentPort.close(); 2342} 2343``` 2344 2345##### Attributes 2346 23471. 2348 2349- Attribute 2350 2351| onmessage?:(event:MessageEvent)=>void | Event handler to be called when the host thread receives a message sent by the worker thread through **parentPort.postMessage**. The event handler is executed in the worker thread. | 2352|---|---| 2353 2354- Example 2355 2356``` 2357// main.js 2358import worker from "@ohos.worker" 2359const worker = new worker.Worker("workers/worker.js"); 2360worker.postMessage("hello world"); 2361 2362// worker.js 2363import worker from "@ohos.worker" 2364const parentPort = worker.parentPort; 2365parentPort.onmessage = function(e) { 2366 console.log("receive main.js message"); 2367} 2368``` 2369 23702. 2371 2372- Attribute 2373 2374| onerror?:(ev: ErrorEvent)=>void | Event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread. | 2375|---|---| 2376 2377- Example 2378 2379``` 2380// main.js 2381import worker from "@ohos.worker" 2382const worker = new worker.Worker("workers/worker.js"); 2383worker.postMessage("hello world"); 2384 2385// worker.js 2386import worker from "@ohos.worker" 2387const parentPort = worker.parentPort; 2388parentPort.onerror = function(e) { 2389 console.log("onerror..."); 2390} 2391 2392``` 2393 23943. 2395 2396- Attribute 2397 2398| onmessageerror?:(event: MessageEvent)=>void | Event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread. | 2399|---|---| 2400 2401- Example 2402 2403``` 2404// main.js 2405import worker from "@ohos.worker" 2406const worker = new worker.Worker("workers/worker.js"); 2407worker.postMessage("hello world"); 2408 2409// worker.js 2410import worker from "@ohos.worker" 2411const parentPort = worker.parentPort; 2412parentPort.onmessageerror = function(e) { 2413 console.log("onmessageerror..."); 2414} 2415``` 2416 2417 2418# Repositories Involved 2419 2420[arkcompiler_ets_runtime](https://gitee.com/openharmony/arkcompiler_ets_runtime/blob/master/README_zh.md) 2421[arkui_ace_engine](https://gitee.com/openharmony/arkui_ace_engine/blob/master/README_zh.md) 2422[arkui_napi](https://gitee.com/openharmony/arkui_napi/blob/master/README_zh.md) 2423 2424# Licenses 2425 2426**js_api_module** can be used under the [Mozilla Public License](https://www.mozilla.org/en-US/MPL/). For the complete license text, see [License](https://gitee.com/openharmony/commonlibrary_ets_utils/blob/master/js_api_module/mozilla_docs.txt). 2427 2428**js_util_module** can be used under the [Mozilla Public License](https://www.mozilla.org/en-US/MPL/). For the complete license text, see [License](https://gitee.com/openharmony/commonlibrary_ets_utils/blob/master/js_util_module/mozilla_docs.txt). 2429 2430**js_concurrent_module** can be used under the [Mozilla Public License](https://www.mozilla.org/en-US/MPL/). For the complete license text, see [License](https://gitee.com/openharmony/commonlibrary_ets_utils/blob/master/js_concurrent_module/mozilla_docs.txt). 2431 2432**js_sys_module** can be used under the [Mozilla Public License](https://www.mozilla.org/en-US/MPL/). For the complete license text, see [License](https://gitee.com/openharmony/commonlibrary_ets_utils/blob/master/js_sys_module/mozilla_docs.txt).