1# ets_utils 2 3- [Submodule](#Submodule) 4 - [1.js_api_module submodule](#1.js_api_module submodule) 5 - [1.1.Introduction](#1.1.Introduction) 6 - [1.2.Contents](#1.2.Contents) 7 - [1.3.Illustrate](#1.3.Illustrate) 8 - [1.3.1.Interface Description](#1.3.1.Interface Description) 9 - [1.3.2.Instructions for use](#1.3.2.Instructions for use) 10 - [2.js_util_module submodule](#2.js_util_module submodule) 11 - [2.1.Introduction](#2.1.Introduction) 12 - [2.2.Contents](#2.2.Contents) 13 - [2.3.Illustrate](#2.3.Illustrate) 14 - [2.3.1.Interface Description](#2.3.1.Interface Description) 15 - [2.3.2.Instructions for use](#2.3.2.Instructions for use) 16 - [3.js_sys_module submodule](#3.js_sys_module submodule) 17 - [3.1.Introduction](#3.1.Introduction) 18 - [3.2.Contents](#3.2.Contents) 19 - [3.3.Illustrate](#3.3.Illustrate) 20 - [3.3.1.Interface Description](#3.3.1.Interface Description) 21 - [3.3.2.Instructions for use](#3.3.2.Instructions for use) 22 - [4.js_concurrent_module submodule](#4.js_concurrent_module submodule) 23 - [4.1.Introduction](#4.1.Introduction) 24 - [4.2.Interface description](#4.2.Interface description) 25 - [4.2.1.Worker object description](#4.2.1.Worker object description) 26 - [4.2.1.1.Interface](#4.2.1.1.Interface) 27 - [4.2.1.2.Attribute](#4.2.1.2.Attribute) 28 - [4.2.2.parentPort object description](#4.2.2.parentPort object description) 29 - [4.2.2.1.Interface](#4.2.2.1.Interface) 30 - [4.2.2.2.Attribute](#4.2.2.2.Attribute) 31- [Related warehouse](#Related warehouse) 32- [License](#License) 33 34## 1.js_api_module_submodule 35### 1.1.Introduction 36 37The interface of URL is used to parse, construct, normalize, and encode URLs. The constructor of URL creates a new URL object. In order to make changes to the resolved components of the URL or to the URL. The URLSearchParams interface defines some practical methods to process URL query strings. 38 39URI Represents a Uniform Resource Identifier (URI) reference. 40 41XML representation refers to extensible markup language. 42 43The XmlSerializer interface is used to generate an xml file. The constructor of XmlSerializer creates a new XmlSerializer object, and calls the method of the XmlSerializer object to generate an xml file. The XmlPullParser interface is used to parse the existing xml file. The constructor of XmlPullParser creates a new XmlPullParser object, and calls the method of the XmlPullParser object to parse the xml file. 44 45### 1.2.Contents 46 47``` 48commomlibrary/ets_utils/js_api_module/ 49├── Class:URL # URL class 50│ ├── new URL(input[, base]) # Create URL object 51│ ├── hash # hash attribute 52│ ├── host # host attribute 53│ ├── hostname # hostname attribute 54│ ├── href # href attribute 55│ ├── origin # origin attribute 56│ ├── password # password attribute 57│ ├── pathname # pathname attribute 58│ ├── port # port attribute 59│ ├── protocol # protocol attribute 60│ ├── search # search attribute 61│ ├── searchParams # searchParams attribute 62│ ├── username # username attribute 63│ ├── toString() # toString method 64│ └── toJSON() # toJSON method 65├── Class: URLSearchParams # URLSearchParams class 66│ ├── new URLSearchParams() # Create URLSearchParams object 67│ ├── new URLSearchParams(string) # Create URLSearchParams object 68│ ├── new URLSearchParams(obj) # Create URLSearchParams object 69│ ├── new URLSearchParams(iterable) # Create URLSearchParams object 70│ ├── append(name, value) # append method 71│ ├── delete(name) # delete method 72│ ├── entries() # entries method 73│ ├── forEach(fn[, thisArg]) # forEach method 74│ ├── get(name) # get method 75│ ├── getAll(name) # getAll method 76│ ├── has(name) # has method 77│ ├── keys() # keys method 78│ ├── set(name, value) # set method 79│ ├── sort() # sort method 80│ ├── toString() # toString method 81│ ├── values() # values method 82│ └── urlSearchParams[Symbol.iterator]() # Create URLSearchParams object 83├── Class:URI # URI class 84│ ├── URI(str: string) # Create URI object 85│ ├── scheme # scheme attribute 86│ ├── authority # authority attribute 87│ ├── ssp # ssp attribute 88│ ├── userinfo # userinfo attribute 89│ ├── host # host attribute 90│ ├── port # port attribute 91│ ├── query # query attribute 92│ ├── fragment # fragment attribute 93│ ├── path # path method 94│ ├── equals(ob: Object) # equals method 95│ ├── normalize() # normalize method 96│ ├── checkIsAbsolute() # checkIsAbsolute method 97│ ├── normalize() # normalize method 98│ ├── toString() # toString method 99├── Class:ConvertXml # ConvertXml class 100│ ├── ConvertXml() # Create convertxml class object 101│ └── convert(xml: string, options: Object) # convert method 102├── Class:XmlSerializer # XmlSerializer class 103│ ├── new XmlSerializer(buffer: ArrayBuffer | DataView, encoding?: string) # Create XmlSerializer class object 104│ ├── setAttributes(name: string, value: string) # Set Attributes method 105│ ├── addEmptyElement(name: string) # Add an empty element method 106│ ├── setDeclaration() # Set the Declaration method 107│ ├── startElement(name: string) # Set the start element method 108│ ├── endElement() # Set the end element method 109│ ├── setNamespace(prefix: string, namespace: string) # Namespace method 110│ ├── setCommnet(text: string) # Set up Commnet method 111│ ├── setCData(text: string) # Set the CData method 112│ ├── setText(text: string) # Set the Text method 113│ ├── setDocType(text: string) # Set DocType method 114└── Class: XmlPullParser # XmlPullParser class 115 ├── new (buffer: ArrayBuffer | DataView, encoding?: string) # Create XmlPullParser object 116 └── parse(option: ParseOptions) # parse method 117``` 118 119### 1.3.Illustrate 120 121#### 1.3.1.Interface Description 122 123 124| Interface name | Illustrate | 125| -------- | -------- | 126| new URL(url: string,base?:string \| URL) | Create and return a URL object that references the URL specified by the absolute URL string, the relative URL string, and the basic URL string. | 127| tostring():string | The stringification method returns a USVString containing the complete URL. It is equivalent to the read-only URL.href. | 128| toJSON():string | This method returns a USVString, which contains a serialized URL version. | 129| new URLSearchParams() | The URLSearchParams() constructor has no parameters. This method creates and returns a new URLSearchParams object. The beginning'?' character will be ignored. | 130| new URLSearchParams(string) | The input parameter of URLSearchParams(string) constructor is string data type. This method creates and returns a new URLSearchParams object. The beginning'?' character will be ignored. | 131| new URLSearchParams(obj) | URLSearchParams(obj) The input parameter of the constructor is the obj data type. This method creates and returns a new URLSearchParams object. The beginning'?' character will be ignored. | 132| new URLSearchParams(iterable) | URLSearchParams(iterable) The input parameter of the constructor is the iterable data type. This method creates and returns a new URLSearchParams object. The beginning'?' character will be ignored. | 133| has(name: string): boolean | Retrieve whether the searchParams object contains name. If yes, it returns true, otherwise it returns false. | 134| set(name: string, value string): void | Retrieve whether the searchParams object contains a key-value pair whose key is name. If not, add the key-value pair, if any, modify the value corresponding to the first key in the object, and delete the remaining key-value pairs whose key is name. | 135| sort(): void | According to the Unicode code point of the key, sort all key/value pairs contained in this object and return undefined. | 136| toString(): string | According to the searchParams object, the query string applicable in the URL is returned. | 137| keys(): iterableIterator\<string> | Return an iterator, which allows iterating through all the key values contained in the object. | 138| values(): iterableIterator\<string> | Returns an iterator, which allows iterating over all the value values contained in the object. | 139| append(name: string, value: string): void | Insert the name, value key-value pair in the searchParams object. | 140| delete(name: string): void | Traverse the searchParams object, find all the names, and delete the corresponding key-value pairs. | 141| get(name: string): string | Retrieve the first name in the searchParams object and return the value corresponding to the name key. | 142| getAll(name: string): string[] | Retrieve all names in the searchParams object and return all the values corresponding to the name key. | 143| entries(): iterableIterator<[string, string]> | Returns an iterator that allows iterating through all key/value pairs contained in the searchParams object. | 144| forEach(): void | Through the callback function to traverse the key-value pairs on the URLSearchParams instance object. | 145| urlSearchParams\[Symbol.iterator]() | Returns an ES6 iterator for each name-value pair in the query string. Each item of the iterator is a JavaScript array. | 146| URI(str: string) | Construct the URI by parsing the given input parameter (String str). This constructor parses the given string strictly in accordance with the grammatical provisions in RFC 2396 Appendix A. | 147| getScheme() | Return the scheme component of this URI, or null if the scheme is not defined. | 148| getAuthority() | Returns the decoded authority component of this URI, or null if authority is not defined. The string returned by this method is the same as the string returned by the getRawAuthority method, except that all escaped octet sequences are decoded. | 149| getSchemeSpecificPart() | Returns the decoding scheme-specific part of this URI. The string returned by this method is the same as the string returned by the getRawSchemeSpecificPart method, except that all escaped octet sequences are decoded. | 150| getUserInfo() | Returns the decoded userinfo component of this URI. The userinfo component of the URI (if defined) only contains characters in unreserved, punctuation, escape, and other categories. | 151| getHost() | Return the host component of this URI, or null if host is not defined. | 152| getPort() | Return the port of this URI, or -1 if the port is not defined. The port component of the URI (if defined) is a non-negative integer. | 153| getQuery() | Returns the decoded query component of this URI, or null if the query is not defined. The string returned by this method is the same as the string returned by the getRawQuery method, except that all escaped octet sequences are decoded. | 154| getFragment() | Returns the decoded fragment component of this URI, or null if the fragment is not defined. The string returned by this method is the same as the string returned by the getRawFragment method, except that all escaped octet sequences are decoded. | 155| getPath() | Returns the decoded path component of this URI, or null if path is not defined. The string returned by this method is the same as the string returned by the getRawPath method, except that all escaped octet sequences are decoded. | 156| equals(ob: Object) | Test whether this URI is equal to another object. If the given object is not a URI, this method immediately returns false. | 157| normalize() | Normalize the path of this URI. If this URI is opaque, or its path is already in normal form, then this URI is returned. Otherwise, a new URI identical to this URI will be constructed. | 158| checkIsAbsolute() | Determine whether this URI is absolute. If and only if it has a scheme component, the URI is absolute and the return value is true, otherwise the return value is false. | 159| toString() | Return the content of this URI as a string. | 160| ConvertXml() | The constructor used to construct the convertxml class object. This constructor does not need to pass in parameters. | 161| convert(xml: string, options: Object) | Returns a JavaScript object that converts an XML string as required by the option. | 162| XmlSerializer(buffer: ArrayBuffer \| DataView, encoding?: string) | Create and return an XmlSerializer object. The XmlSerializer object passes two parameters. The first parameter is ArrayBuffer or DataView, and the second parameter is the file format (UTF-8 by default). | 163| setAttributes(name: string, value: string): void | Write the Attributes attribute to the xml file. | 164| addEmptyElement(name: string): void | Write an empty element. | 165| setDeclaration(): void | Set the Declaration to use the encoding to write the xml declaration. For example: <? xml version="1.0" encoding="utf-8"> | 166| startElement(name: string): void | Write the elemnet start tag with the given name.| 167| endElement(): void | Write the end tag of the element. | 168| setNamespace(prefix: string, namespace: string): void | Write the namespace of the current element tag. | 169| setCommnet(text: string): void | Write the comment attribute. | 170| setCData(text: string): void | Write the CData attribute. | 171| setText(text: string): void | Write the Text property. | 172| setDocType(text: string): void | Write the DocType attribute. | 173| XmlPullParser(buffer: ArrayBuffer \| DataView, encoding?: string) | Create and return an XmlPullParser object. The XmlPullParser object passes two parameters. The first parameter is ArrayBuffer or DataView, and the second parameter is the file format (default is UTF-8). | 174| parse(option: ParseOptions): void | This interface is used to parse xml. The ParseOptions parameter is an interface containing five optional parameters {supportDoctype?: boolea ignoreNameSpace?: boolean tagValueCallbackFunction?: (name: string, value: string) => boolean attributeValueCallbackFunction?: (name: string, value: string) => boolean) tokenValueCallbackFunction?: (eventType: EventType, value: ParseInfo) => boolean }. The input parameter 1 of the tokenValueCallbackFunction callback function is the event type, and the input parameter 2 is the info interface containing get attributes such as getColumnNumber and getDepth. The user can obtain the depth and other information in the current parsing process through methods such as info.getDepth(). | 175#### 1.3.2.Instructions for use 176 177The usage of each interface is as follows: 178 179 1801、new URL(url: string,base?:string|URL) 181``` 182let b = new URL('https://developer.mozilla.org'); // => 'https://developer.mozilla.org/' 183 184let a = new URL( 'sca/./path/path/../scasa/text', 'http://www.example.com'); 185// => 'http://www.example.com/sca/path/scasa/text' 186``` 1872、tostring():string 188``` 189const url = new URL('http://10.0xFF.O400.235:8080/directory/file?query#fragment'); 190url.toString() // => 'http://10.0xff.o400.235:8080/directory/file?query#fragment' 191 192const url = new URL("http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"); 193url.toString() // => 'http://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]/index.html' 194 195const url = new URL("http://username:password@host:8080/directory/file?query#fragment"); 196url.toString() // => 'http://username:password@host:8080/directory/file?query#fragment' 197``` 1983、toJSON():string 199``` 200const url = new URL("https://developer.mozilla.org/en-US/docs/Web/API/URL/toString"); 201url.toJSON(); // => 'https://developer.mozilla.org/en-US/docs/Web/API/URL/toString' 202``` 2034、new URLSearchParams() 204``` 205let params = new URLSearchParams('foo=1&bar=2'); 206``` 2075、new URLSearchParams(string) 208``` 209params = new URLSearchParams('user=abc&query=xyz'); 210console.log(params.get('user')); 211// Prints 'abc' 212``` 2136、new URLSearchParams(obj) 214``` 215const params = new URLSearchParams({ 216 user: 'abc', 217 query: ['first', 'second'] 218}); 219console.log(params.getAll('query')); 220// Prints [ 'first,second' ] 221``` 2227、new URLSearchParams(iterable) 223``` 224let params; 225 226// Using an array 227params = new URLSearchParams([ 228 ['user', 'abc'], 229 ['query', 'first'], 230 ['query', 'second'], 231]); 232console.log(params.toString()); 233// Prints 'user = abc & query = first&query = second' 234``` 2358、has(name: string): boolean 236``` 237console.log(params.has('bar')); // =>true 238``` 2399、set(name: string, value string): void 240``` 241params.set('baz', 3); 242``` 24310、sort(): void 244``` 245params .sort(); 246``` 24711、toString(): string 248``` 249console.log(params .toString()); // =>bar=2&baz=3&foo=1' 250``` 25112、keys(): iterableIterator\<string> 252``` 253for(var key of params.keys()) { 254 console.log(key); 255} // =>bar baz foo 256``` 25713、values(): iterableIterator\<string> 258``` 259for(var value of params.values()) { 260 console.log(value); 261} // =>2 3 1 262``` 26314、append(name: string, value: string): void 264``` 265params.append('foo', 3); // =>bar=2&baz=3&foo=1&foo=3 266``` 26715、delete(name: string): void 268``` 269params.delete('baz'); // => bar=2&foo=1&foo=3 270``` 27116、get(name: string): string 272``` 273params.get('foo'); // => 1 274``` 27517、getAll(name: string): string[] 276``` 277params.getAll('foo'); // =>[ '1', '3' ] 278``` 27918、entries(): iterableIterator<[string, string]> 280``` 281for(var pair of searchParams.entries()) { 282 console.log(pair[0]+ ', '+ pair[1]); 283} // => bar, 2 foo, 1 foo, 3 284``` 28519、forEach(): void 286``` 287url.searchParams.forEach((value, name, searchParams) => { 288 console.log(name, value, url.searchParams === searchParams); 289}); 290// => foo 1 true 291// => bar 2 true 292``` 29320、urlSearchParams[Symbol.iterator] () 294``` 295const params = new URLSearchParams('foo=bar&xyz=baz'); 296for (const [name, value] of params) { 297 console.log(name, value); 298} 299// Prints: 300// foo bar 301// xyz bar 302``` 303 304 30521、URI(String str) 306``` 307let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 308``` 30922、scheme 310``` 311let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 312gaogao.scheme // => "http"; 313``` 31423、authority 315``` 316let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 317gaogao.authority // => "gg:gaogao@www.baidu.com:99"; 318``` 31924、ssp 320``` 321let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 322gaogao.ssp " // => gg:gaogao@www.baidu.com:99/path/path?query"; 323``` 32425、userinfo 325``` 326let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 327gaogao.userinfo // => "gg:gaogao"; 328``` 32926、host 330``` 331let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 332gaogao.host // => "www.baidu.com"; 333``` 33427、port 335``` 336let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 337gaogao.port // => "99"; 338``` 33928、query 340``` 341let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 342gaogao.query // => "query"; 343``` 34429、fragment 345``` 346let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 347gaogao.fragment // => "fagment"; 348``` 34930、path 350``` 351let gaogao = new Uri.URI('http://gg:gaogao@www.baidu.com:99/path/path?query#fagment'); 352gaogao.path // => "/path/path"; 353``` 35431、equals(Object ob) 355``` 356let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path1?query#fagment'); 357let gaogao1 = gaogao; 358let res = gaogao.equals(gaogao1); 359console.log(res); // => true; 360``` 36132、normalize() 362``` 363let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path/66./../././mm/.././path1?query#fagment'); 364let res = gaogao.normalize(); 365console.log(res.path); // => "/path/path1" 366console.log(res.toString()); // => "http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/path/path1?query#fagment" 367``` 36833、checkIsAbsolute() 369``` 370let gaogao = new Uri.URI('f/tp://username:password@www.baidu.com:88/path?query#fagment'); 371let res = gaogao.checkIsAbsolute(); 372console.log(res); //=> false; 373``` 37434、toString() 375``` 376let gaogao = new Uri.URI('http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/../../path/.././../aa/bb/cc?query#fagment'); 377let res = gaogao.toString(); 378console.log(res.toString()); // => 'http://gg:gaogao@[1:0:0:1:2:1:2:1]:99/../../path/.././../aa/bb/cc?query#fagment'; 379``` 380 381 38235、ConvertXml() 383``` 384var convertml = new convertXml.ConvertXml(); 385``` 38636、convert(xml: string, options: Object) 387``` 388var result = convertml.convert(xml, {compact: false, spaces: 4}); 389``` 39037、new XmlSerializer(buffer: ArrayBuffer | DataView, encoding?: string) 391``` 392 393var arrayBuffer = new ArrayBuffer(1024); 394var bufView = new DataView(arrayBuffer); 395var thatSer = new xml.XmlSerializer(bufView); 396``` 39738、setDeclaration():void 398``` 399var thatSer = new xml.XmlSerializer(bufView); 400thatSer.setDeclaration() // => <?xml version="1.0" encoding="utf-8"?>; 401``` 40239、setCommnet(text: string):void 403``` 404var thatSer = new xml.XmlSerializer(bufView); 405thatSer.setCommnet("Hello, World!"); // => <!--Hello, World!-->; 406``` 40740、setCData(text: string) :void 408``` 409var thatSer = new xml.XmlSerializer(bufView); 410thatSer.setDocType('root SYSTEM "http://www.test.org/test.dtd"'); // => <![CDATA[root SYSTEM \“http://www.test.org/test.dtd\”]]> 411``` 41241、setDocType(text: string):void 413``` 414var thatSer = new xml.XmlSerializer(bufView); 415thatSer.setDocType("foo"); // => <!DOCTYPE foo> 416``` 41742、setNamespace(prefix: string, namespace: string): void 41843、startElement(name: string): void 41944、setAttributes(name: string, value: string): void 42045、endElement(): void 42146、setText(text: string): void 422``` 423var thatSer = new xml.XmlSerializer(bufView); 424thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); 425thatSer.startElement("table"); 426thatSer.setAttributes("importance", "high"); 427thatSer.setText("Happy"); 428endElement(); // => <h:table importance="high" xmlns:h="http://www.w3.org/TR/html4/">Happy</h:table> 429``` 43047、addEmptyElement(name: string): void 431``` 432var thatSer = new xml.XmlSerializer(bufView); 433thatSer.addEmptyElement("b"); // => <b/> 434``` 43548、new (buffer: ArrayBuffer | DataView, encoding?: string) 436``` 437var strXml = 438 '<?xml version="1.0" encoding="utf-8"?>' + 439 '<note importance="high" logged="true">' + 440 ' <title>Happy</title>' + 441 '</note>'; 442var arrayBuffer = new ArrayBuffer(strXml.length*2); 443var bufView = new Uint8Array(arrayBuffer); 444var strLen = strXml.length; 445for (var i = 0; i < strLen; ++i) { 446 bufView[i] = strXml.charCodeAt(i);//设置arraybuffer 方式 447} 448var that = new xml.XmlPullParser(arrayBuffer); 449 450``` 45149、parse(option: ParseOptions): void 452``` 453var strXml = 454 '<?xml version="1.0" encoding="utf-8"?>' + 455 '<note importance="high" logged="true">' + 456 ' <title>Happy</title>' + 457 '</note>'; 458var arrayBuffer = new ArrayBuffer(strXml.length*2); 459var bufView = new Uint8Array(arrayBuffer); 460var strLen = strXml.length; 461for (var i = 0; i < strLen; ++i) { 462 bufView[i] = strXml.charCodeAt(i); 463} 464var that = new xml.XmlPullParser(arrayBuffer); 465var arrTag = {}; 466arrTag[0] = '132'; 467var i = 1; 468function func(key, value){ 469 arrTag[i] = 'key:'+key+' value:'+ value.getDepth(); 470 i++; 471 return true; 472} 473var options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func}; 474that.parse(options); 475``` 476 477## 2.js_util_module submodule 478### 2.1.Introduction 479The interface of util is used for character Textencoder, TextDecoder and HelpFunction module.The TextEncoder represents a text encoder that accepts a string as input, encodes it in UTF-8 format, and outputs UTF-8 byte stream. The TextDecoder interface represents a text decoder. The decoder takes the byte stream as the input and outputs the String string. HelpFunction is mainly used to callback and promise functions, write and output error codes, and format class strings. 480Encodes all bytes from the specified u8 array into a newly-allocated u8 array using the Base64 encoding scheme or Encodes the specified byte array into a String using the Base64 encoding scheme.Decodes a Base64 encoded String or input u8 array into a newly-allocated u8 array using the Base64 encoding scheme.The rational number is mainly to compare rational numbers and obtain the numerator and denominator.The LruBuffer algorithm replaces the least used data with new data when the buffer space is insufficient. The algorithm derives from the need to access resources: recently accessed data can be Will visit again in the near future. The least accessed data is the least valuable data that should be kicked out of the cache space. The Scope interface is used to describe the valid range of a field. The constructor for the Scope instance is used to create objects with specified lower and upper bounds and require that these objects be comparable. 481### 2.2.contants 482 483``` 484commomlibrary/ets_utils/js_util_module/ 485├── Class:TextEncoder # TextEncoder class 486│ ├── new TextEncoder() # create textencoder object 487│ ├── encode() # encode method 488│ ├── encoding # encoding property 489│ └── encodeInto() # encodeInto method 490├── Class:TextDecoder # TextDecoder class 491│ ├── new TextDecoder() # create TextDecoder object 492│ ├── decode() # decode method 493| ├── decodeWithStream() # decodeWithStream method 494│ ├── encoding # encoding property 495│ ├── fatal # fatal property 496│ └── ignoreBOM # ignoreBOM property 497├── printf() # printf method 498├── getErrorString() # getErrorString method 499├── callbackWrapper() # callbackWrapper method 500├── promiseWrapper() # promiseWrapper method 501├── Class:Base64 # Base64 class 502│ ├── new Base64() # create Base64 object 503│ ├── encodeSync() # encodeSync method 504│ ├── encodeToStringSync() # encodeToStringSync method 505│ ├── decodeSync() # decodeSync method 506│ ├── encode() # encode method 507│ ├── encodeToString() # encodeToString method 508│ └── decode() # decode method 509├── Class:RationalNumber # RationalNumber class 510│ ├── new RationalNumber() # create RationalNumber object 511│ ├── createRationalFromString() # creatRationalFromString method 512│ ├── compareTo() # compareTo method 513│ ├── equals() # equals method 514│ ├── valueOf() # valueOf method 515│ ├── getCommonDivisor() # getCommonDivisor method 516│ ├── getDenominator() # getDenominator method 517│ ├── getNumerator() # getNumerator method 518│ ├── isFinite() # isFinite method 519│ ├── isNaN() # isNaN method 520│ ├── isZero() # isZero method 521│ └── toString() # toString method 522├── Class:LruBuffer # LruBuffer class 523│ ├── new LruBuffer() # create RationalNumber object 524│ ├── updateCapacity() # updateCapacity method 525│ ├── toString() # toString method 526│ ├── values() # values method 527│ ├── length # attribute of length 528│ ├── getCapacity() # getCapacity method 529│ ├── clear() # clear method 530│ ├── getCreateCount # getCreateCount method 531│ ├── getMissCount() # getMissCount method 532│ ├── getRemovalCount() # getRemovalCount method 533│ ├── getMatchCount() # getMatchCount method 534│ ├── getPutCount() # getPutCount method 535│ ├── isEmpty() # isEmpty method 536│ ├── get() # get method 537│ ├── put() # put method 538│ ├── keys() # keys method 539│ ├── remove() # remove method 540│ ├── afterRemoval() # afterRemoval method 541│ ├── contains() # contains method 542│ ├── createDefault() # createDefault method 543│ ├── entries() # entries method 544│ └── [Symbol.iterator]() # Symboliterator method 545├── Class:Scope # Scope class 546| ├── constructor() # create Scope object 547| ├── toString() # toString method 548| ├── intersect() # intersect method 549| ├── intersect() # intersect method 550| ├── getUpper() # getUpper method 551| ├── getLower() # getLower method 552| ├── expand() # expand method 553| ├── expand() # expand method 554| ├── expand() # expand method 555| ├── contains() # contains method 556| ├── contains() # contains method 557| └── clamp() # clamp method 558└── Class:Types # Types class 559 ├── isAnyArrayBuffer() # isAnyArrayBuffer method 560 ├── isArrayBufferView() # isArrayBufferView method 561 ├── isArgumentsObject() # isArgumentsObject method 562 ├── isArrayBuffer() # isArrayBuffer method 563 ├── isAsyncFunction() # isAsyncFunction method 564 ├── isBigInt64Array() # isBigInt64Array method 565 ├── isBigUint64Array() # isBigUint64Array method 566 ├── isBooleanObject() # isBooleanObject method 567 ├── isBoxedPrimitive() # isBoxedPrimitive method 568 ├── isDataView() # isDataView method 569 ├── isDate() # isDate method 570 ├── isExternal() # isExternal method 571 ├── isFloat32Array() # isFloat32Arraymethod 572 ├── isFloat64Array() # isFloat64Array method 573 ├── isGeneratorFunction() # isGeneratorFunction method 574 ├── isGeneratorObject() # isGeneratorObject method 575 ├── isInt8Array() # isInt8Array method 576 ├── isInt16Array() # isInt16Array method 577 ├── isInt32Array() # isInt32Array method 578 ├── isMap() # isMap method 579 ├── isMapIterator() # isMapIterator method 580 ├── isModuleNamespaceObject() # isModuleNamespaceObject method 581 ├── isNativeError() # isNativeError method 582 ├── isNumberObject() # isNumberObject method 583 ├── isPromise() # isPromise method 584 ├── isProxy() # isProxy method 585 ├── isRegExp() # isRegExp method 586 ├── isSet() # isSet method 587 ├── isSetIterator() # isSetIterator method 588 ├── isSharedArrayBuffer() # isSharedArrayBuffer method 589 ├── isStringObject() # isStringObject method 590 ├── isSymbolObject() # isSymbolObject method 591 ├── isTypedArray() # isTypedArray method 592 ├── isUint8Array() # isUint8Array method 593 ├── isUint8ClampedArray() # isUint8ClampedArray method 594 ├── isUint16Array() # isUint16Array method 595 ├── isUint32Array() # isUint32Array method 596 ├── isWeakMap() # isWeakMap method 597 └── isWeakSet() # isWeakSet method 598``` 599 600### 2.3.Description 601 602#### 2.3.1.Interface description 603| Interface name | Description | 604| -------- | -------- | 605| constructor(encoding? : string) | Constructor, the parameter encoding indicates the format of encoding. Default utf-8, Support gb18030, gbk, gb2312. | 606| readonly encoding : string | In the TextEncoder module, get the encoding format. | 607| encode(input : string) : Uint8Array | Input string string, encoding according to encoding and output uint8 byte stream. | 608| encodeInto(input : string, dest : Uint8Array) : {read : number, written : number} | Enter the string string, dest represents the storage location after encoding, and returns an object, read represents the number of characters that have been encoded,and written represents the size of bytes occupied by the encoded characters. | 609| constructor(encoding? : string, options? : {fatal? : boolean, ignoreBOM? : boolean}) | Constructor, the first parameter encoding indicates the format of decoding.The second parameter represents some attributes.Fatal in the attribute indicates whether an exception is thrown, and ignoreBOM indicates whether to ignore the bom flag. | 610| readonly encoding : string | In the TextDecoder module, get the set decoding format. | 611| readonly fatal : boolean | Get the setting that throws the exception. | 612| readonly ignoreBOM : boolean | Get whether to ignore the setting of the bom flag. | 613| decode(input : Uint8Array, options?: { stream?: false }) : string | Input the data to be decoded, and solve the corresponding string character string.The first parameter input represents the data to be decoded, and the second parameter options represents a bool flag, which means that additional data will be followed. The default is false. | 614| decodeWithStream(input : Uint8Array, options?: { stream?: false }) : string | Input the data to be decoded, and solve the corresponding string character string.The first parameter input represents the data to be decoded, and the second parameter options represents a bool flag, which means that additional data will be followed. The default is false. | 615| encodeSync(src: Uint8Array): Uint8Array; | Encodes all bytes in the specified u8 array into the newly allocated u8 array using the Base64 encoding scheme. | 616| encodeToStringSync(src: Uint8Array): string; | Encodes the specified byte array as a String using the Base64 encoding scheme. | 617| decodeSync(src: Uint8Array \| string): Uint8Array; | Decodes the Base64-encoded string or input u8 array into the newly allocated u8 array using the Base64 encoding scheme. | 618| encode(src: Uint8Array): Promise\<Uint8Array\>; | Asynchronously encodes all bytes in the specified u8 array into the newly allocated u8 array using the Base64 encoding scheme. | 619| encodeToString(src: Uint8Array): Promise\<string\>; | Asynchronously encodes the specified byte array into a String using the Base64 encoding scheme. | 620| decode(src: Uint8Array \| string): Promise\<Uint8Array\>; | Use the Base64 encoding scheme to asynchronously decode a Base64-encoded string or input u8 array into a newly allocated u8 array. | 621| static createRationalFromString(rationalString: string): RationalNumber | Create a RationalNumber object based on the given string. | 622| compareTo(another: RationalNumber): number | Compare the current RationalNumber object with the given object. | 623| equals(obj: object): number | Check if the given object is the same as the current RationalNumber object.| 624| valueOf(): number | Take the current RationalNumber object to an integer value or a floating point value. | 625| static getCommonDivisor(number1: number, number2: number,): number | Obtain the greatest common divisor of two specified numbers. | 626| getDenominator(): number | Get the denominator of the current RationalNumber object. | 627| getNumerator(): number | Get the numerator of the current RationalNumber object. | 628| isFinite(): boolean | Check that the current RationalNumber object is limited. | 629| isNaN(): boolean | Check whether the current RationalNumber object represents a non-number (NaN) value. | 630| isZero(): boolean | Check whether the current RationalNumber object represents a zero value. | 631| toString(): string | Get the string representation of the current RationalNumber object. | 632| constructor(capacity?: number) | The Create Default constructor is used to create a new LruBuffer instance with a default capacity of 64. | 633| updateCapacity(newCapacity: number): void | Updates the buffer capacity to the specified capacity. This exception is thrown if newCapacity is less than or equal to 0. | 634| toString(): string | Returns the string representation of the object and outputs the string representation of the object. | 635| values(): V[ ] | Gets a list of all values in the current buffer, and the output returns a list of all values in the current buffer in ascending order, from most recently accessed to least recently accessed. | 636| length: number | represents the total number of values in the current buffer. The output returns the total number of values in the current buffer. | 637| getCapacity(): number | Gets the capacity of the current buffer. The output returns the capacity of the current buffer. | 638| clear(): void | The key value pairs are cleared from the current buffer, after the key value is cleared, the afterRemoval () method is invoked to perform subsequent operations in turn. | 639| getCreateCount(): number | Get the number of times the returned value of createdefault(), and output the number of times the returned value of createdefault(). | 640| getMissCount(): number | Get the number of times the query value does not match, and output the number of times the query value does not match. | 641| getRemovalCount(): number | Gets the number of evictions from the buffer, and outputs the number of evictions from the buffer. | 642| getMatchCount(): number | Obtain the number of successful matching of query values, and output the number of successful matching of query values. | 643| getPutCount(): number | Gets the number of times the value was added to the buffer, and the output returns the number of times the value was added to the buffer. | 644| isEmpty(): boolean | Checks whether the current buffer is empty and returns true if the current buffer does not contain any values. | 645| get(key: K):V \| undefined | Indicates the key to query. If the specified key exists in the buffer, the value associated with the key will be returned; Otherwise, undefined is returned. | 646| put(key: K, value: V): V | Adding the key value pair to the buffer and outputting the value associated with the added key; If the key to be added already exists, the original value is returned. If the key or value is empty, this exception is thrown. | 647| keys(): K[ ] | Get the key list of the value in the current buffer, and the output returns the key list sorted from the most recent access to the least recent access. | 648| remove(key: K):V \| undefined | Deletes the specified key and its associated value from the current buffer. | 649| afterRemoval(isEvict: boolean, key: K, value: V, newValue: V): void | Perform subsequent operations after deleting the value. | 650| contains(key: K): boolean | Checks whether the current buffer contains the specified key, and returns true if the buffer contains the specified key. | 651| createDefault(key: K): V | If the value of a specific key is not calculated, subsequent operations are performed. The parameter represents the missing key, and the output returns the value associated with the key. | 652| entries(): [K,V] | Allows you to iterate over all key value pairs contained in this object. The keys and values of each pair are objects. | 653| \[Symbol.iterator\](): [K,V]| Returns a two-dimensional array in the form of key value pairs. | 654| constructor(lowerObj: ScopeType, upperObj: ScopeType) | Creates and returns a Scope object that creates a constructor for a scope instance that specifies a lower and upper bound. | 655| toString():string | The stringification method returns a string representation that contains the current range. | 656| intersect(range: Scope): Scope | Gets the intersection of the given range and the current range. | 657| intersect(lowerObj: ScopeType, upperObj: ScopeType): Scope | Gets the intersection of the current range with a given lower and upper bound range. | 658| getUpper(): ScopeType | Gets the upper bound of the current scope. | 659| getLower(): ScopeType | Gets the lower bound of the current scope. | 660| expand(lowerObj: ScopeType, upperObj: ScopeType): Scope | Creates and returns a union that includes the current range and a given lower and upper bound. | 661| expand(range: Scope): Scope | Creates and returns a union that includes the current range and the given range. | 662| expand(value: ScopeType): Scope | Creates and returns a union that includes the current range and the given value. | 663| contains(value: ScopeType): boolean | Checks whether the given value is included in the current range. | 664| contains(range: Scope): boolean | Checks whether the given range is within the current range. | 665| clamp(value: ScopeType): ScopeType | Clips the specified value to the current range. | 666| function printf(format: string, ...args: Object[]): string | The util.format() method returns a formatted string using the first argument as a printf-like format string which can contain zero or more format specifiers. | 667| function getErrorString(errno: number): string | The geterrorstring () method uses a system error number as a parameter to return system error information. | 668| function callbackWrapper(original: Function): (err: Object, value: Object) => void | Takes an async function (or a function that returns a Promise) and returns a function following the error-first callback style, i.e. taking an (err, value) => ... callback as the last argument. In the callback, the first argument will be the rejection reason (or null if the Promise resolved), and the second argument will be the resolved value. | 669| function promiseWrapper(original: (err: Object, value: Object) => void): Object | Takes a function following the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument, and returns a version that returns promises. | 670| isAnyArrayBuffer(value: Object): boolean | Check whether the entered value is of arraybuffer or sharedarraybuffer type. | 671| isArrayBufferView(value: Object): boolean | Check whether the entered value is napi_ int8_ array or napi_ uint8_ array or naPi_ uint8_ clamped_ array or naPi_ int16_ array or naPi_ uint16_ array or napi_ int32_ array or napi_ uint32_ array or napi_ float32_ array or napi_ float64_ array array or DataView type. | 672| isArgumentsObject(value: Object): boolean | Check whether the entered value is an arguments object type. | 673| isArrayBuffer(value: Object): boolean | Check whether the entered value is of arraybuffer type. | 674| isAsyncFunction(value: Object): boolean | Check whether the value entered is an asynchronous function type. | 675| isBigInt64Array(value: Object): boolean | Check whether the entered value is of bigint64array array type. | 676| isBigUint64Array(value: Object): boolean | Check whether the entered value is of biguint64array array array type. | 677| isBooleanObject(value: Object): boolean | Check whether the entered value is a Boolean object type. | 678| isBoxedPrimitive(value: Object): boolean | Check whether the entered value is a Boolean or number or string or symbol object type. | 679| isDataView(value: Object): boolean | Check whether the entered value is of DataView type. | 680| isDate(value: Object): boolean | Check whether the entered value is of type date. | 681| isExternal(value: Object): boolean | Check whether the entered value is a native external value type. | 682| isFloat32Array(value: Object): boolean | Check whether the entered value is of float32array array type. | 683| isFloat64Array(value: Object): boolean | Check whether the entered value is of float64array array type. | 684| isGeneratorFunction(value: Object): boolean | Check whether the input value is a generator function type. | 685| isGeneratorObject(value: Object): boolean | Check whether the entered value is a generator object type. | 686| isInt8Array(value: Object): boolean | Check whether the entered value is of int8array array type. | 687| isInt16Array(value: Object): boolean | Check whether the entered value is the int16array type. | 688| isInt32Array(value: Object): boolean | Check whether the entered value is the int32array array type. | 689| isMap(value: Object): boolean | Check whether the entered value is of map type. | 690| isMapIterator(value: Object): boolean | Check whether the entered value is the iterator type of map. | 691| isModuleNamespaceObject(value: Object): boolean | Check whether the entered value is the module namespace object object type. | 692| isNativeError(value: Object): boolean | Check whether the value entered is of type error. | 693| isNumberObject(value: Object): boolean | Check whether the entered value is of the number object type. | 694| isPromise(value: Object): boolean | Check whether the entered value is of promise type. | 695| isProxy(value: Object): boolean | Check whether the value entered is of proxy type. | 696| isRegExp(value: Object): boolean | Check whether the entered value is of type regexp. | 697| isSet(value: Object): boolean | Check whether the entered value is of type set. | 698| isSetIterator(value: Object): boolean | Check whether the entered value is the iterator type of set. | 699| isSharedArrayBuffer(value: Object): boolean | Check whether the entered value is of type sharedarraybuffer. | 700| isStringObject(value: Object): boolean | Check whether the entered value is a string object type. | 701| isSymbolObject(value: Object): boolean | Check whether the entered value is a symbol object type. | 702| isTypedArray(value: Object): boolean | Check whether the entered value is a type contained in typedarray. | 703| isUint8Array(value: Object): boolean | Check whether the entered value is the uint8array array type. | 704| isUint8ClampedArray(value: Object): boolean | Check whether the entered value is the uint8clapedarray array type. | 705| isUint16Array(value: Object): boolean | Check whether the entered value is the uint16array array array type. | 706| isUint32Array(value: Object): boolean | Check whether the entered value is the uint32array array type. | 707| isWeakMap(value: Object): boolean | Check whether the entered value is of type weakmap. | 708| isWeakSet(value: Object): boolean | Check whether the entered value is of type weakset. | 709 710Each specifier in printf is replaced with a converted value from the corresponding parameter. Supported specifiers are: 711| Stylized character | Style requirements | 712| -------- | -------- | 713| %s: | String will be used to convert all values except BigInt, Object and -0. | 714| %d: | Number will be used to convert all values except BigInt and Symbol. | 715| %i: | parseInt(value, 10) is used for all values except BigInt and Symbol. | 716| %f: | parseFloat(value) is used for all values expect Symbol. | 717| %j: | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | 718| %o: | Object. A string representation of an object with generic JavaScript object formatting. Similar to util.inspect() with options { showHidden: true, showProxy: true }. This will show the full object including non-enumerable properties and proxies. | 719| %O: | Object. A string representation of an object with generic JavaScript object formatting. Similar to util.inspect() without options. This will show the full object not including non-enumerable properties and proxies. | 720| %c: | CSS. This specifier is ignored and will skip any CSS passed in. | 721| %%: | single percent sign ('%'). This does not consume an argument. | 722 723#### 2.3.2.Instruction for use 724 725 726The use methods of each interface are as follows: 727 7281.readonly encoding() 729 730``` 731import util from '@ohos.util' 732var textEncoder = new util.TextEncoder(); 733var getEncoding = textEncoder.encoding(); 734``` 7352.encode() 736``` 737import util from '@ohos.util' 738var textEncoder = new util.TextEncoder(); 739var result = textEncoder.encode('abc'); 740``` 7413.encodeInto() 742``` 743import util from '@ohos.util' 744var textEncoder = new util.TextEncoder(); 745var obj = textEncoder.encodeInto('abc', dest); 746``` 7474.textDecoder() 748``` 749import util from '@ohos.util' 750var textDecoder = new util.textDecoder("utf-16be", {fatal : true, ignoreBOM : false}); 751``` 7525.readonly encoding() 753``` 754import util from '@ohos.util' 755var textDecoder = new util.textDecoder("utf-16be", {fatal : true, ignoreBOM : false}); 756var getEncoding = textDecoder.encoding(); 757``` 7586.readonly fatal() 759``` 760import util from '@ohos.util' 761var textDecoder = new util.textDecoder("utf-16be", {fatal : true, ignoreBOM : false}); 762var fatalStr = textDecoder.fatal(); 763``` 7647.readonly ignoreBOM() 765``` 766import util from '@ohos.util' 767var textDecoder = new util.textDecoder("utf-16be", {fatal : true, ignoreBOM : false}); 768var ignoreBom = textDecoder.ignoreBOM(); 769``` 7708.decode() 771``` 772import util from '@ohos.util' 773var textDecoder = new util.textDecoder("utf-16be", {fatal : true, ignoreBOM : false}); 774var result = textDecoder.decode(input, {stream : true}); 775``` 7769.decodeWithStream() 777``` 778import util from '@ohos.util' 779var textDecoder = new util.textDecoder("utf-16be", {fatal : true, ignoreBOM : false}); 780var result = textDecoder.decodeWithStream(input, {stream : true}); 781``` 78210.printf() 783``` 784import util from '@ohos.util' 785var format = "%%%o%%%i%s"; 786var value = function aa(){}; 787var value1 = 1.5; 788var value2 = "qwer"; 789var result = util.printf(format,value,value1,value2); 790``` 79111.getErrorString() 792``` 793import util from '@ohos.util' 794var errnum = 13; 795var result = util.getErrorString(errnum); 796``` 79712.callbackWrapper() 798``` 799import util from '@ohos.util' 800async function promiseFn() { 801 return Promise.resolve('value'); 802}; 803var cb = util.callbackWrapper(promiseFn); 804cb((err, ret) => { 805 expect(err).strictEqual(null); 806 expect(ret).strictEqual('value'); 807}) 808``` 80913.promiseWrapper() 810``` 811import util from '@ohos.util' 812function aysnFun(str1, str2, callback) { 813 if (typeof str1 === 'string' && typeof str1 === 'string') { 814 callback(null, str1 + str2); 815 } else { 816 callback('type err'); 817 } 818} 819let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); 820newPromiseObj.then(res => { 821 expect(res).strictEqual('HelloWorld'); 822}) 823``` 82414.encodeSync() 825``` 826import util from '@ohos.util' 827var that = new util.Base64(); 828var array = new Uint8Array([115,49,51]); 829var result = that.encodeSync(array); 830``` 83115.encodeToStringSync() 832``` 833import util from '@ohos.util' 834var that = new util.Base64(); 835var array = new Uint8Array([115,49,51]); 836var result = that.encodeToStringSync(array); 837``` 83816.decodeSync() 839``` 840import util from '@ohos.util' 841var that = new util.Base64() 842var buff = 'czEz'; 843var result = that.decodeSync(buff); 844``` 84517.encode() 846``` 847import util from '@ohos.util' 848var that = new util.Base64() 849var array = new Uint8Array([115,49,51]); 850await that.encode(array).then(val=>{ 851}) 852done() 853``` 85418.encodeToString() 855``` 856import util from '@ohos.util' 857var that = new util.Base64() 858var array = new Uint8Array([115,49,51]); 859await that.encodeToString(array).then(val=>{ 860}) 861done() 862``` 86319.decode() 864``` 865import util from '@ohos.util' 866var that = new util.Base64() 867var buff = 'czEz'; 868await that.decode(buff).then(val=>{ 869}) 870done() 871``` 87220.createRationalFromString() 873``` 874import util from '@ohos.util' 875var pro = new util.RationalNumber(0, 0); 876var res = pro.createRationalFromString("-1:2"); 877var result1 = res.value(); 878``` 87921.compareTo() 880``` 881import util from '@ohos.util' 882var pro = new util.RationalNumber(2, 1); 883var proc = new util.RationalNumber(3, 4); 884var res = pro.compareTo(proc); 885``` 88622.equals() 887``` 888import util from '@ohos.util' 889var pro = new util.RationalNumber(2, 1); 890var proc = new util.RationalNumber(3, 4); 891var res = pro.equals(proc); 892``` 89323.valueOf() 894``` 895import util from '@ohos.util' 896var pro = new util.RationalNumber(2, 1); 897var res = pro.value(); 898``` 89924.getCommonDivisor() 900``` 901import util from '@ohos.util' 902var pro = new util.RationalNumber(0, 0); 903var res = pro.getCommonDivisor(4, 8); 904``` 90525.getDenominator() 906``` 907import util from '@ohos.util' 908var pro = new util.RationalNumber(2, 1); 909var res = pro.getDenominator(); 910``` 91126.getNumerator() 912``` 913import util from '@ohos.util' 914var pro = new util.RationalNumber(-2, 1); 915var res = pro.getNumerator(); 916``` 91727.isFinite() 918``` 919import util from '@ohos.util' 920var pro = new util.RationalNumber(-2, 1); 921var res = pro.isFinite(); 922``` 92328.isNaN() 924``` 925import util from '@ohos.util' 926var pro = new util.RationalNumber(-2, 1); 927var res = pro.isNaN(); 928``` 92929.isZero() 930``` 931import util from '@ohos.util' 932var pro = new util.RationalNumber(-2, 1); 933var res = pro.isZero(); 934 935``` 93630.toString() 937``` 938import util from '@ohos.util' 939var pro = new util.RationalNumber(-2, 1); 940var res = pro.toString(); 941 942``` 94331.updateCapacity() 944``` 945import util from '@ohos.util' 946var pro = new util.LruBuffer(); 947var result = pro.updateCapacity(100); 948``` 94932.toString() 950``` 951import util from '@ohos.util' 952var pro = new util.LruBuffer(); 953pro.put(2,10); 954pro.get(2); 955pro.remove(20); 956var result = pro.toString(); 957``` 95833.values() 959``` 960import util from '@ohos.util' 961var pro = new util.LruBuffer(); 962pro.put(2,10); 963pro.put(2,"anhu"); 964pro.put("afaf","grfb"); 965var result = pro.values(); 966``` 96734.length 968``` 969import util from '@ohos.util' 970var pro = new util.LruBuffer(); 971pro.put(2,10); 972pro.put(1,8); 973var result = pro.length; 974``` 97535.getCapacity() 976``` 977import util from '@ohos.util' 978var pro = new util.LruBuffer(); 979var result = pro.getCapacity(); 980``` 98136.clear() 982``` 983import util from '@ohos.util' 984var pro = new util.LruBuffer(); 985pro.put(2,10); 986pro.clear(); 987``` 98837.getCreateCount() 989``` 990import util from '@ohos.util' 991var pro = new util.LruBuffer(); 992pro.put(1,8); 993var result = pro.getCreateCount(); 994``` 99538.getMissCount() 996``` 997import util from '@ohos.util' 998var pro = new util.LruBuffer(); 999pro.put(2,10); 1000pro.get(2) 1001var result = pro.getMissCount(); 1002``` 100339.getRemovalCount() 1004``` 1005import util from '@ohos.util' 1006var pro = new util.LruBuffer(); 1007pro.put(2,10); 1008pro.updateCapacity(2); 1009pro.put(50,22); 1010var result = pro.getRemovalCount(); 1011``` 101240.getMatchCount() 1013``` 1014import util from '@ohos.util' 1015var pro = new util.LruBuffer(); 1016pro.put(2,10); 1017pro.get(2); 1018var result = pro.getMatchCount(); 1019``` 102041.getPutCount() 1021``` 1022import util from '@ohos.util' 1023var pro = new util.LruBuffer(); 1024pro.put(2,10); 1025var result = pro.getPutCount(); 1026``` 102742.isEmpty() 1028``` 1029import util from '@ohos.util' 1030var pro = new util.LruBuffer(); 1031pro.put(2,10); 1032var result = pro.isEmpty(); 1033``` 103443.get() 1035``` 1036import util from '@ohos.util' 1037var pro = new util.LruBuffer(); 1038pro.put(2,10); 1039var result = pro.get(2); 1040``` 104144.put() 1042``` 1043import util from '@ohos.util' 1044var pro = new util.LruBuffer(); 1045var result = pro.put(2,10); 1046``` 104745.keys() 1048``` 1049import util from '@ohos.util' 1050var pro = new util.LruBuffer(); 1051 pro.put(2,10); 1052var result = pro.keys(); 1053``` 105446.remove() 1055``` 1056import util from '@ohos.util' 1057var pro = new util.LruBuffer(); 1058pro.put(2,10); 1059var result = pro.remove(20); 1060``` 106147.contains() 1062``` 1063import util from '@ohos.util' 1064var pro = new util.LruBuffer(); 1065pro.put(2,10); 1066var result = pro.contains(20); 1067``` 106848.createDefault() 1069``` 1070import util from '@ohos.util' 1071var pro = new util.LruBuffer(); 1072var result = pro.createDefault(50); 1073``` 107449.entries() 1075``` 1076import util from '@ohos.util' 1077var pro = new util.LruBuffer(); 1078pro.put(2,10); 1079var result = pro.entries(); 1080``` 108150.\[Symbol.iterator\]() 1082``` 1083import util from '@ohos.util' 1084var pro = new util.LruBuffer(); 1085pro.put(2,10); 1086var result = pro[symbol.iterator](); 1087``` 108851.afterRemoval() 1089``` 1090import util from '@ohos.util' 1091var arr = []; 1092class ChildLruBuffer extends util.LruBuffer 1093{ 1094 constructor() 1095 { 1096 super(); 1097 } 1098 static getInstance() 1099 { 1100 if(this.instance == null) 1101 { 1102 this.instance = new ChildLruBuffer(); 1103 } 1104 return this.instance; 1105 } 1106 afterRemoval(isEvict, key, value, newValue) 1107 { 1108 if (isEvict === false) 1109 { 1110 arr = [key, value, newValue]; 1111 } 1112 } 1113} 1114ChildLruBuffer.getInstance().afterRemoval(false,10,30,null) 1115``` 1116Construct a new class in the Scope interface to implement the compareTo method. 1117 1118``` 1119class Temperature { 1120 constructor(value) { 1121 this._temp = value; 1122 } 1123 compareTo(value) { 1124 return this._temp >= value.getTemp(); 1125 } 1126 getTemp() { 1127 return this._temp; 1128 } 1129 toString() { 1130 return this._temp.toString(); 1131 } 1132} 1133``` 1134 113552.constructor() 1136 1137``` 1138var tempLower = new Temperature(30); 1139var tempUpper = new Temperature(40); 1140var range = new Scope(tempLower, tempUpper); 1141``` 1142 114353.toString() 1144 1145``` 1146var tempLower = new Temperature(30); 1147var tempUpper = new Temperature(40); 1148var range = new Scope(tempLower, tempUpper); 1149var result = range.toString() // => [30,40] 1150``` 1151 115254.intersect() 1153 1154``` 1155var tempLower = new Temperature(30); 1156var tempUpper = new Temperature(40); 1157var range = new Scope(tempLower, tempUpper); 1158var tempMiDF = new Temperature(35); 1159var tempMidS = new Temperature(39); 1160var rangeFir = new Scope(tempMiDF, tempMidS); 1161var result = range.intersect(rangeFir) // => [35,39] 1162``` 1163 116455.intersect() 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.intersect(tempMiDF, tempMidS) // => [35,39] 1173``` 1174 117556.getUpper() 1176 1177``` 1178var tempLower = new Temperature(30); 1179var tempUpper = new Temperature(40); 1180var range = new Scope(tempLower, tempUpper); 1181var result = range.getUpper() // => 40 1182``` 1183 118457.getLower() 1185 1186``` 1187var tempLower = new Temperature(30); 1188var tempUpper = new Temperature(40); 1189var range = new Scope(tempLower, tempUpper); 1190var result = range.getLower() // => 30 1191``` 1192 119358.expand() 1194 1195``` 1196var tempLower = new Temperature(30); 1197var tempUpper = new Temperature(40); 1198var tempMiDF = new Temperature(35); 1199var tempMidS = new Temperature(39); 1200var range = new Scope(tempLower, tempUpper); 1201var result = range.expand(tempMiDF, tempMidS) // => [30,40] 1202``` 1203 120459.expand() 1205 1206``` 1207var tempLower = new Temperature(30); 1208var tempUpper = new Temperature(40); 1209var tempMiDF = new Temperature(35); 1210var tempMidS = new Temperature(39); 1211var range = new Scope(tempLower, tempUpper); 1212var rangeFir = new Scope(tempMiDF, tempMidS); 1213var result = range.expand(rangeFir) // => [30,40] 1214``` 1215 121660.expand() 1217 1218``` 1219var tempLower = new Temperature(30); 1220var tempUpper = new Temperature(40); 1221var tempMiDF = new Temperature(35); 1222var range = new Scope(tempLower, tempUpper); 1223var result = range.expand(tempMiDF) // => [30,40] 1224``` 1225 122661.contains() 1227 1228``` 1229var tempLower = new Temperature(30); 1230var tempUpper = new Temperature(40); 1231var tempMiDF = new Temperature(35); 1232var range = new Scope(tempLower, tempUpper); 1233var result = range.contains(tempMiDF) // => true 1234``` 1235 123662.contains() 1237 1238``` 1239var tempLower = new Temperature(30); 1240var tempUpper = new Temperature(40); 1241var range = new Scope(tempLower, tempUpper); 1242var tempLess = new Temperature(20); 1243var tempMore = new Temperature(45); 1244var rangeSec = new Scope(tempLess, tempMore); 1245var result = range.contains(rangeSec) // => true 1246``` 1247 124863.clamp() 1249 1250``` 1251var tempLower = new Temperature(30); 1252var tempUpper = new Temperature(40); 1253var tempMiDF = new Temperature(35); 1254var range = new Scope(tempLower, tempUpper); 1255var result = range.clamp(tempMiDF) // => 35 1256``` 125764.isAnyArrayBuffer() 1258``` 1259import util from '@ohos.util' 1260var proc = new util.Types(); 1261var result = proc.isAnyArrayBuffer(new ArrayBuffer([])) 1262``` 126365.isArrayBufferView() 1264``` 1265import util from '@ohos.util' 1266var proc = new util.Types(); 1267var result = proc.isArrayBufferView(new DataView(new ArrayBuffer(16))); 1268``` 126966.isArgumentsObject() 1270``` 1271import util from '@ohos.util' 1272function foo() { 1273 var result = proc.isArgumentsObject(arguments); 1274 } 1275var f = foo(); 1276``` 127767.isArrayBuffer() 1278``` 1279import util from '@ohos.util' 1280var proc = new util.Types(); 1281var result = proc.isArrayBuffer(new ArrayBuffer([])); 1282``` 128368.isAsyncFunction() 1284``` 1285import util from '@ohos.util' 1286var proc = new util.Types(); 1287var result = proc.isAsyncFunction(async function foo() {}); 1288``` 128969.isBigInt64Array() 1290``` 1291import util from '@ohos.util' 1292var proc = new util.Types(); 1293var result = proc.isBigInt64Array(new Int16Array([])); 1294``` 129570.isBigUint64Array() 1296``` 1297import util from '@ohos.util' 1298var proc = new util.Types(); 1299var result = proc.isBigUint64Array(new Int16Array([])); 1300``` 130171.isBooleanObject() 1302``` 1303import util from '@ohos.util' 1304var proc = new util.Types(); 1305var result = proc.isBooleanObject(new Boolean(false)); 1306``` 130772.isBoxedPrimitive() 1308``` 1309import util from '@ohos.util' 1310var proc = new util.Types(); 1311var result = proc.isBoxedPrimitive(new Boolean(false)); 1312``` 131373.isDataView() 1314``` 1315import util from '@ohos.util' 1316var proc = new util.Types(); 1317const ab = new ArrayBuffer(20); 1318var result = proc.isDataView(new DataView(ab)); 1319``` 132074.isDate() 1321``` 1322import util from '@ohos.util' 1323var proc = new util.Types(); 1324var result = proc.isDate(new Date()); 1325``` 132675.isExternal() 1327``` 1328import util from '@ohos.util' 1329const data = util.createExternalType(); 1330var reult13 = proc.isExternal(data); 1331``` 133276.isFloat32Array() 1333``` 1334import util from '@ohos.util' 1335var proc = new util.Types(); 1336var result = proc.isFloat32Array(new Float32Array([])); 1337``` 133877.isFloat64Array() 1339``` 1340import util from '@ohos.util' 1341var proc = new util.Types(); 1342var result = proc.isFloat64Array(new Float64Array([])); 1343``` 134478.isGeneratorFunction() 1345``` 1346import util from '@ohos.util' 1347var proc = new util.Types(); 1348var result = proc.isGeneratorFunction(function* foo() {}); 1349``` 135079.isGeneratorObject() 1351``` 1352import util from '@ohos.util' 1353var proc = new util.Types(); 1354function* foo() {} 1355const generator = foo(); 1356var result = proc.isGeneratorObject(generator); 1357``` 135880.isInt8Array() 1359``` 1360import util from '@ohos.util' 1361var proc = new util.Types(); 1362var result = proc.isInt8Array(new Int8Array([])); 1363``` 136481.isInt16Array() 1365``` 1366import util from '@ohos.util' 1367var proc = new util.Types(); 1368var result = proc.isInt16Array(new Int16Array([])); 1369``` 137082.isInt32Array() 1371``` 1372import util from '@ohos.util' 1373var proc = new util.Types(); 1374var result = proc.isInt32Array(new Int32Array([])); 1375``` 137683.isMap() 1377``` 1378import util from '@ohos.util' 1379var proc = new util.Types(); 1380var result = proc.isMap(new Map()); 1381``` 138284.isMapIterator() 1383``` 1384import util from '@ohos.util' 1385var proc = new util.Types(); 1386var result = proc.isMapIterator(map.keys()); 1387``` 138885.isModuleNamespaceObject() 1389``` 1390import util from '@ohos.util' 1391var proc = new util.Types(); 1392var result = proc.isModuleNamespaceObject(util); 1393``` 139486.isNativeError() 1395``` 1396import util from '@ohos.util' 1397var proc = new util.Types(); 1398var result = proc.isNativeError(new TypeError()); 1399``` 140087.isNumberObject() 1401``` 1402import util from '@ohos.util' 1403var proc = new util.Types(); 1404var result = proc.isNumberObject(new Number(0)); 1405``` 140688.isPromise() 1407``` 1408import util from '@ohos.util' 1409var proc = new util.Types(); 1410var result = proc.isPromise(Promise.resolve(42)); 1411``` 141289.isProxy() 1413``` 1414import util from '@ohos.util' 1415var proc = new util.Types(); 1416const target = {}; 1417const proxy = new Proxy(target, {}); 1418var result = proc.isProxy(proxy); 1419``` 142090.isRegExp() 1421``` 1422import util from '@ohos.util' 1423var proc = new util.Types(); 1424var result = proc.isRegExp(new RegExp('abc')); 1425``` 142691.isSet() 1427``` 1428import util from '@ohos.util' 1429var proc = new util.Types(); 1430var result = proc.isSet(new Set()); 1431``` 143292.isSetIterator() 1433``` 1434import util from '@ohos.util' 1435var proc = new util.Types(); 1436const set = new Set(); 1437var result = proc.isSetIterator(set.keys()); 1438``` 143993.isSharedArrayBuffer() 1440``` 1441import util from '@ohos.util' 1442var proc = new util.Types(); 1443var result = proc.isSharedArrayBuffer(new ArrayBuffer([])); 1444``` 144594.isStringObject() 1446``` 1447import util from '@ohos.util' 1448var proc = new util.Types(); 1449var result = proc.isStringObject(new String('foo')); 1450``` 145195.isSymbolObject() 1452``` 1453import util from '@ohos.util' 1454var proc = new util.Types(); 1455const symbols = Symbol('foo'); 1456var result = proc.isSymbolObject(Object(symbols)); 1457``` 145896.isTypedArray() 1459``` 1460import util from '@ohos.util' 1461var proc = new util.Types(); 1462var result = proc.isTypedArray(new Float64Array([])); 1463``` 146497.isUint8Array() 1465``` 1466import util from '@ohos.util' 1467var proc = new util.Types(); 1468var result = proc.isUint8Array(new Uint8Array([])); 1469``` 147098.isUint8ClampedArray() 1471``` 1472import util from '@ohos.util' 1473var proc = new util.Types(); 1474var result = proc.isUint8ClampedArray(new Uint8ClampedArray([])); 1475``` 147699.isUint16Array() 1477``` 1478import util from '@ohos.util' 1479var proc = new util.Types(); 1480var result = proc.isUint16Array(new Uint16Array([])); 1481``` 1482100.isUint32Array() 1483``` 1484import util from '@ohos.util' 1485var proc = new util.Types(); 1486var result = proc.isUint32Array(new Uint32Array([])); 1487``` 1488101.isWeakMap() 1489``` 1490import util from '@ohos.util' 1491var proc = new util.Types(); 1492var result = proc.isWeakMap(new WeakMap()); 1493``` 1494102.isWeakSet() 1495``` 1496import util from '@ohos.util' 1497var proc = new util.Types(); 1498var result = proc.isWeakSet(new WeakSet()); 1499``` 1500 1501## 3.js_sys_module submodule 1502### 3.1.Introduction 1503Process is mainly used to obtain the relevant ID of the process, obtain and modify the working directory of the process, exit and close the process. The childprocess object can be used to create a new process. The main process can obtain the standard input and output of the child process, send signals and close the child process. 1504### 3.2.Directory 1505 1506``` 1507commomlibrary/ets_utils/js_sys_module/ 1508├── Class:PROCESS # class of PROCESS 1509├── Uid # attribute of Uid 1510├── Gid # attribute of Gid 1511├── EUid # attribute of EUid 1512├── EGid # attribute of EGid 1513├── Groups # attribute of Groups 1514├── Pid # attribute of Pid 1515├── Ppid # attribute of Ppid 1516├── chdir() # method of chdir 1517├── uptime() # method of uptime 1518├── kill() # method of kill 1519├── abort() # method of abort 1520├── on() # method of on 1521├── tid # method of tid 1522├── getStartRealtime() # method of getStartRealtime 1523├── getAvailableCores() # method of getAvailableCores 1524├── getPastCputime() # method of getPastCputime 1525├── isIsolatedProcess() # method of isIsolatedProcess 1526├── is64Bit() # method of is64Bit 1527├── isAppUid() # method of isAppUid 1528├── getUidForName() # method of getUidForName 1529├── getThreadPriority() # method of getThreadPriority 1530├── getSystemConfig() # method of getSystemConfig 1531├── getEnvironmentVar() # method of getEnvironmentVar 1532├── exit() # method of exit 1533├── cwd() # method of cwd 1534├── off() # method of off 1535├── runCmd() # method of runCmd 1536└─── Class:CHILDPROCESS # class of CHILDPROCESS 1537 ├── close() # method of close 1538 ├── kill() # method of kill 1539 ├── getOutput() # method of getOutput 1540 ├── getErrorOutput() # method of getErrorOutput 1541 ├── wait() # method of wait 1542 ├── killed # attribute of killed 1543 ├── pid # attribute of pid 1544 ├── ppid # attribute of ppid 1545 └── exitCode # attribute of exitCode 1546``` 1547 1548### 3.3.Description 1549 1550#### 3.3.1.Interface description 1551| Interface name | description | 1552| -------- | -------- | 1553| const uid :number | returns the digital user ID of the process. | 1554| const gid :number | returns the numeric group ID of the process. | 1555| const euid :number | returns the numeric valid user identity of the process. | 1556| const egid :number | returns the numeric valid group ID of the node.js process. | 1557| const groups :number[] | returns an array with supplementary group ID. | 1558| const pid :number | returns the PID of the process. | 1559| const ppid :number | returns the PID of the parent process of the current process. | 1560| chdir(dir:string) :void | change the current working directory of the node.js process. | 1561| uptime() :number | returns the number of seconds the current system has been running. | 1562| Kill(pid:number, signal:number) :boolean | send the signal to the identified process PID, and true means the sending is successful. | 1563| abort() :void | cause the node.js process to exit immediately and generate a core file. | 1564| on(type:string ,listener:EventListener) :void | used to store events triggered by users. | 1565| exit(code:number):void | cause the node.js process to exit immediately. | 1566| cwd():string | returns the current working directory of the node.js process. | 1567| off(type: string): boolean | clear the events stored by the user. True means the clearing is successful. | 1568| runCmd(command: string, options?: { timeout : number, killSignal : number \| string, maxBuffer : number }): ChildProcess |through runcmd, you can fork a new process to run a shell and return the childprocess object. The first parameter command refers to the shell to be run, and the second parameter options refers to some running parameters of the child process. These parameters mainly refer to timeout, killsignal and maxbuffer. If timeout is set, the child process will send a signal killsignal after timeout is exceeded. Maxbuffer is used to limit the maximum stdout and stderr sizes that can be received. | 1569| wait(): Promise\<number> | is used to wait for the child process to run and return the promise object, whose value is the exit code of the child process. | 1570| getOutput(): Promise\<Uint8Array> | used to get the standard output of the child process. | 1571| getErrorOutput(): Promise\<Uint8Array> | used to get the standard error output of the child process. | 1572| const tid:number | Returns the TID of the process. | 1573| getStartRealtime() :number | Gets the real time elapsed (in milliseconds) from system startup to process startup. | 1574| getAvailableCores() :number[] | Gets the CPU kernel available to the current process on the multi-core device. | 1575| getPastCputime() :number | Gets the CPU time (in milliseconds) from the start of the process to the current time. | 1576| isIsolatedProcess(): boolean | Check if the process is quarantined. | 1577| is64Bit(): boolean | Check whether the process is running in a 64 bit environment. | 1578| isAppUid(v:number): boolean | Checks whether the specified uid belongs to a specific application. | 1579| getUidForName(v:string): number | Obtain the user group ID to which the user belongs according to the user name | 1580| getThreadPriority(v:number): number | Gets the thread priority based on the specified TID. | 1581| getSystemConfig(name:number): number | Gets the configuration of the system according to the specified system configuration name. | 1582| getEnvironmentVar(name:string): string | Obtain the corresponding value according to the name of the environment variable. | 1583| close(): void | used to close the running child process. | 1584| kill(signal: number \| string): void | used to send signals to child processes. | 1585| readonly killed: boolean | indicates whether the signal is sent successfully, and true indicates that the signal is sent successfully. | 1586| readonly exitCode: number | indicates the exit code of the child process. | 1587| readonly pid: number | represents the child process ID. | 1588| readonly ppid: number | represents the main process ID. | 1589 1590#### 3.3.2.Interface instructions 1591 1592Example of using interface: 15931.uid() 1594``` 1595uid(){ 1596 var res = Process.uid; 1597} 1598``` 15992.gid() 1600``` 1601gid(){ 1602 var result = Process.gid; 1603} 1604``` 16053.euid() 1606``` 1607euid(){ 1608 var and = Process.euid; 1609} 1610``` 16114.egid() 1612``` 1613egid(){ 1614 var resb = Process.egid; 1615} 1616``` 16175.groups() 1618``` 1619groups(){ 1620 var answer = Process.groups; 1621} 1622``` 16236.pid() 1624``` 1625pid(){ 1626 var result = Process.pid; 1627} 1628``` 16297.ppid() 1630``` 1631ppid(){ 1632 var result = Process.ppid; 1633} 1634``` 16358.chdir() 1636``` 1637chdir(){ 1638 Process.chdir("123456"); 1639} 1640``` 16419.uptime() 1642``` 1643uptime(){ 1644 var num = Process.uptime(); 1645} 1646``` 164710.kill() 1648``` 1649kill(){ 1650 var ansu = Process.kill(5,23); 1651} 1652``` 165311.abort() 1654``` 1655abort(){ 1656 Process.abort(); 1657} 1658``` 165912.on() 1660``` 1661on(){ 1662 function add(num){ 1663 var value = num + 5; 1664 return value; 1665 } 1666 Process.on("add",add); 1667} 1668``` 166913.exit() 1670``` 1671exit(){ 1672 Process.exit(15); 1673} 1674``` 167514.Cwd() 1676``` 1677Cwd(){ 1678 var result = Process.cwd(); 1679} 1680``` 168115.off() 1682 1683``` 1684off(){ 1685 var result = Process.off("add"); 1686} 1687``` 168816.runCmd() 1689``` 1690runCmd(){ 1691 var child = process.runCmd('echo abc') 1692 // killSignal can be a number or a string 1693 var child = process.runCmd('echo abc;', {killSignal : 'SIGKILL'}); 1694 var child = process.runCmd('sleep 5; echo abc;', {timeout : 1, killSignal : 9, maxBuffer : 2}) 1695} 1696``` 169717.wait() 1698``` 1699wait() 1700{ 1701 var child = process.runCmd('ls') 1702 var status = child.wait(); 1703 status.then(val => { 1704 console.log(val); 1705 }) 1706} 1707``` 170818.getOutput() 1709``` 1710getOutput(){ 1711 var child = process.runCmd('echo bcd;'); 1712 var res = child.getOutput(); 1713 child.wait(); 1714 res.then(val => { 1715 console.log(val); 1716 }) 1717} 1718``` 171919.getErrorOutput() 1720``` 1721getErrorOutput(){ 1722 var child = process.runCmd('makdir 1.txt'); // execute an error command 1723 var res = child.getErrorOutput(); 1724 child.wait(); 1725 res.then(val => { 1726 console.log(val); 1727 }) 1728} 1729``` 173020.close() 1731``` 1732close(){ 1733 var child = process.runCmd('ls; sleep 5s;') 1734 var result = child.close() 1735} 1736``` 173721.kill() 1738``` 1739kill(){ 1740 var child = process.runCmd('ls; sleep 5s;') 1741 var result = child.kill('SIGHUP'); 1742 child.wait(); 1743 var temp = child.killed; 1744} 1745``` 174622.killed 1747``` 1748{ 1749 var child = process.runCmd('ls; sleep 5;') 1750 child.kill(3); 1751 var killed_ = child.killed; 1752 child.wait(); 1753} 1754``` 175523.exitCode 1756``` 1757{ 1758 var child = process.runCmd('ls; sleep 5;') 1759 child.kill(9); 1760 child.wait(); 1761 var exitCode_ = child.exitCode; 1762} 1763``` 176424.pid 1765``` 1766pid 1767{ 1768 var child = process.runCmd('ls; sleep 5;') 1769 var pid_ = child.pid; 1770 child.wait(); 1771} 1772``` 177325.ppid 1774``` 1775ppid 1776{ 1777 var child = process.runCmd('ls; sleep 5;') 1778 var ppid_ = child.ppid; 1779 child.wait(); 1780} 1781``` 178226.tid 1783``` 1784tid(){ 1785 var ansu = Process.tid; 1786} 1787``` 178827.isIsolatedProcess() 1789``` 1790isIsolatedProcess(){ 1791 var ansu = Process.isIsolatedProcess()(); 1792} 1793``` 179428.isAppUid() 1795``` 1796isAppUid(){ 1797 var ansu = Process.isAppUid(10000); 1798} 1799``` 180029.is64Bit() 1801``` 1802is64Bit(){ 1803 var ansu = Process.is64Bit(); 1804} 1805``` 180630.getUidForName() 1807``` 1808getUidForName(){ 1809 var buf = "root"; 1810 var ansu = Process.getUidForName(buf); 1811} 1812``` 181331.getEnvironmentVar() 1814``` 1815getEnvironmentVar(){ 1816 var ansu = Process.getEnvironmentVar('USER'); 1817} 1818``` 181932.getAvailableCores() 1820``` 1821getAvailableCores(){ 1822 var ansu = Process.getAvailableCores(); 1823} 1824``` 182533.getThreadPriority() 1826``` 1827getThreadPriority(){ 1828 var result = Process.getTid(); 1829 var ansu = getThreadPriority(result); 1830} 1831``` 183234.getStartRealtime() 1833``` 1834getStartRealtime(){ 1835 var ansu = Process.getStartRealtime(); 1836} 1837``` 183835.getPastCputime() 1839``` 1840getPastCputime(){ 1841 var ansu = Process.getPastCputime(); 1842} 1843``` 184436.getSystemConfig() 1845``` 1846getSystemConfig(){ 1847 var _SC_ARG_MAX = 0; 1848 var ansu = Process.getSystemConfig(_SC_ARG_MAX) 1849} 1850``` 1851 1852## 4.js_concurrent_module submodule 1853 1854### 4.1.Introduction 1855 1856Worker enables JS to have the ability of multithreading, and completes the communication between worker thread and host thread through PostMessage. 1857 1858### 4.2.Interface description 1859For interface implementation, see: js_concurrent_module/jsapi/worker 1860 1861#### 4.2.1.Worker object description 1862 1863The object object used by the host thread to communicate with the worker thread. 1864 1865##### 4.2.1.1.Interface 1866 18671. 1868 1869- name 1870 1871|constructor(scriptURL:string, options? WorkerOptions) | worker constructor to Creates a worker instance | 1872|---|---| 1873 1874- example 1875 1876``` 1877import worker from "@ohos.worker" 1878const worker = new worker.Worker("workers/worker.js"); 1879``` 1880 18812. 1882 1883- name 1884 1885| postMessage(message:Object, options?:PostMessageOptions) | Sends a message to the worker thread | 1886|---|---| 1887| postMessage(message:Object, transfer:ArrayBuffer[]) | Sends a message to the worker thread | 1888 1889- example 1890 1891``` 1892// example 1 1893import worker from "@ohos.worker" 1894const worker = new worker.Worker("workers/worker.js"); 1895worker.postMessage("hello world"); 1896 1897// example 2 1898import worker from "@ohos.worker" 1899const worker = new worker.Worker("workers/worker.js"); 1900var buffer = new ArrayBuffer(8); 1901worker.postMessage(buffer, [buffer]); 1902``` 1903 19043. 1905 1906- name 1907 1908| on(type:string, listener:EventListener) | Adds an event listener to the worker | 1909|---|---| 1910 1911- example 1912 1913``` 1914import worker from "@ohos.worker" 1915const worker = new worker.Worker("workers/worker.js"); 1916worker.on("alert", (e)=>{ 1917 console.log("worker on..."); 1918}) 1919``` 1920 19214. 1922 1923- name 1924 1925| once(type:string, listener:EventListener) | Adds an event listener to the worker and removes the event listener automically after it is invoked once | 1926|---|---| 1927 1928- example 1929 1930``` 1931import worker from "@ohos.worker" 1932const worker = new worker.Worker("workers/worker.js"); 1933worker.once("alert", (e)=>{ 1934 console.log("worker on..."); 1935}) 1936``` 1937 19385. 1939 1940- name 1941 1942| off(type:string, listener?:EventListener) | Removes an event listener to the worker | 1943|---|---| 1944 1945- example 1946 1947``` 1948import worker from "@ohos.worker" 1949const worker = new worker.Worker("workers/worker.js"); 1950worker.off("alert"); 1951``` 1952 19536. 1954 1955- name 1956 1957| terminate() | Terminates the worker thread to stop the worker from receiving messages | 1958|---|---| 1959 1960- example 1961 1962``` 1963import worker from "@ohos.worker" 1964const worker = new worker.Worker("workers/worker.js"); 1965worker.terminate(); 1966``` 1967 19687. 1969 1970- name 1971 1972| removeEventListener(type:string, listener?:EventListener) | Removes an event defined for the worker | 1973|---|---| 1974 1975- example 1976 1977``` 1978import worker from "@ohos.worker" 1979const worker = new worker.Worker("workers/worker.js"); 1980worker.removeEventListener("alert"); 1981``` 1982 19838. 1984 1985- name 1986 1987| dispatchEvent(event: Event) | Dispatches the event defined for the worker | 1988|---|---| 1989 1990- example 1991 1992``` 1993import worker from "@ohos.worker" 1994const worker = new worker.Worker("workers/worker.js"); 1995worker.dispatchEvent({type:"alert"}); 1996``` 1997 19989. 1999 2000- name 2001 2002| removeAllListener() | Removes all event listeners for the worker | 2003|---|---| 2004 2005- example 2006 2007``` 2008import worker from "@ohos.worker" 2009const worker = new worker.Worker("workers/worker.js"); 2010worker.removeAllListener(); 2011``` 2012 2013##### 4.2.1.2.Attribute 2014 20151. 2016 2017- name 2018 2019| onexit?:(code:number)=>void | The onexit attribute of the worker specifies the event handler to be called when the worker exits. The handler is executed in the host thread | 2020|---|---| 2021 2022- example 2023 2024``` 2025import worker from "@ohos.worker" 2026const worker = new worker.Worker("workers/worker.js"); 2027worker.onexit = function(e) { 2028 console.log("onexit..."); 2029} 2030``` 2031 20322. 2033 2034- name 2035 2036| onerror?:(ev:ErrorEvent)=>void | The onerror attribute of the worker specifies the event handler to be called when an exception occurs during worker execution. The event handler is executed in the host thread | 2037|---|---| 2038 2039- example 2040 2041``` 2042import worker from "@ohos.worker" 2043const worker = new worker.Worker("workers/worker.js"); 2044worker.onerror = function(e) { 2045 console.log("onerror..."); 2046} 2047``` 2048 20493. 2050 2051- name 2052 2053| onmessage?:(ev:MessageEvent)=>void | The onmessage attribute of the worker specifies the event handler to be called then the host thread receives a message created by itself and sent by the worker through the parentPort.postMessage. The event handler is executed in the host thread | 2054|---|---| 2055 2056- example 2057 2058``` 2059import worker from "@ohos.worker" 2060const worker = new worker.Worker("workers/worker.js"); 2061worker.onmessage = function(e) { 2062 console.log("onmessage..."); 2063} 2064``` 2065 20664. 2067 2068- name 2069 2070| onmessageerror?:(event:MessageEvent)=>void | The onmessage attribute of the worker specifies the event handler when the worker receives a message that cannot be serialized. The event handler is executed in the host thread | 2071|---|---| 2072 2073- example 2074 2075``` 2076import worker from "@ohos.worker" 2077const worker = new worker.Worker("workers/worker.js"); 2078worker.onmessageerror = function(e) { 2079 console.log("onmessageerror..."); 2080} 2081``` 2082 2083#### 4.2.2.parentPort object description 2084 2085Object of the worker thread used to communicate with the host thread 2086 2087##### 4.2.2.1.Interface 2088 20891. 2090 2091- name 2092 2093| postMessage(message:Object, options?:PostMessageOptions) | Send a message to host thread | 2094|---|---| 2095| postMessage(message:Object, transfer:ArrayBuffer[]) | Send a message to host thread | 2096 2097- example 2098 2099``` 2100// main.js 2101import worker from "@ohos.worker" 2102const worker = new worker.Worker("workers/worker.js"); 2103worker.postMessage("hello world"); 2104 2105// worker.js 2106import worker from "@ohos.worker" 2107const parentPort = worker.parentPort; 2108parentPort.onmessage = function(e) { 2109 parentPort.postMessage("hello world from worker.js"); 2110} 2111``` 2112 21132. 2114 2115- name 2116 2117| close() | Close the worker thread to stop the worker from receiving messages | 2118|---|---| 2119 2120- example 2121 2122``` 2123// main.js 2124import worker from "@ohos.worker" 2125const worker = new worker.Worker("workers/worker.js"); 2126worker.postMessage("hello world"); 2127 2128// worker.js 2129import worker from "@ohos.worker" 2130const parentPort = worker.parentPort; 2131parentPort.onmessage = function(e) { 2132 parentPort.close(); 2133} 2134``` 2135 2136##### 4.2.2.2.Attribute 2137 21381. 2139 2140- name 2141 2142| onmessage?:(event:MessageEvent)=>void | The onmessage attribute of parentPort specifies the event handler to be called then the worker thread receives a message sent by the host thread through worker postMessage. The event handler is executed in the worker thread | 2143|---|---| 2144 2145- example 2146 2147``` 2148// main.js 2149import worker from "@ohos.worker" 2150const worker = new worker.Worker("workers/worker.js"); 2151worker.postMessage("hello world"); 2152 2153// worker.js 2154import worker from "@ohos.worker" 2155const parentPort = worker.parentPort; 2156parentPort.onmessage = function(e) { 2157 console.log("receive main.js message"); 2158} 2159``` 2160 21612. 2162 2163- name 2164 2165| onerror?:(ev: ErrorEvent)=>void | The onerror attribute of parentPort specifies the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread | 2166|---|---| 2167 2168- example 2169 2170``` 2171// main.js 2172import worker from "@ohos.worker" 2173const worker = new worker.Worker("workers/worker.js"); 2174worker.postMessage("hello world"); 2175 2176// worker.js 2177import worker from "@ohos.worker" 2178const parentPort = worker.parentPort; 2179parentPort.onerror = function(e) { 2180 console.log("onerror..."); 2181} 2182 2183``` 2184 21853. 2186 2187- name 2188 2189| onmessageerror?:(event: MessageEvent)=>void | The onmessage attribute of parentPort specifies the event handler to be called then the worker receives a message that cannot be deserialized. The event handler is executed in the worker thread. | 2190|---|---| 2191 2192- example 2193 2194``` 2195// main.js 2196import worker from "@ohos.worker" 2197const worker = new worker.Worker("workers/worker.js"); 2198worker.postMessage("hello world"); 2199 2200// worker.js 2201import worker from "@ohos.worker" 2202const parentPort = worker.parentPort; 2203parentPort.onmessageerror = function(e) { 2204 console.log("onmessageerror..."); 2205} 2206``` 2207 2208### Repositories Involved 2209 2210- ace_ace_engine(foundation/arkui/ace_engine-readme.md) 2211- ace_napi(foundation/arkui/napi-readme.md) 2212 2213## Related warehouse 2214[ets_utils Subsystem](commonlibrary/ets_utils/README.en.md) 2215 2216## License 2217 2218URL is available under [Mozilla license](https://www.mozilla.org/en-US/MPL/), and the documentation is detailed in [documentation](https://gitee.com/openharmony/js_api_module/blob/master/mozilla_docs.txt). See [LICENSE](https://gitee.com/openharmony-sig/commonlibrary_ets_utils/blob/master/LICENSE) for the full license text.