• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.util.stream (Stream Base Class)
2
3The stream module provides APIs to process basic types of streams. With streams, data is read or written by chunk, instead of being loaded to the memory at a time.
4
5There are four fundamental stream types: writable streams ([Writable](#writable)), readable streams ([Readable](#readable)), duplex streams ([Duplex](#duplex)), and transform streams ([Transform](#transform)).
6
7> **NOTE**
8>
9> The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version.
10
11## Modules to Import
12
13```ts
14import { stream  } from '@kit.ArkTS';
15```
16
17## Writable
18
19Stream to which data can be written. A writable stream allows data to be written to a target, which can be a file, an HTTP response, a standard output, another stream, or the like.
20
21### Properties
22
23**Atomic service API**: This API can be used in atomic services since API version 12.
24
25**System capability**: SystemCapability.Utils.Lang
26
27| Name   | Type     | Read-Only| Optional | Description       |
28| ------- | -------- | ------ | ------ | ----------- |
29| writableObjectMode  | boolean   | Yes  | No| Whether the writable stream works in object mode. The value **true** means that the stream is configured in object mode, and **false** means the opposite. Currently, only raw data (string and Uint8Array) is supported, and the return value is **false**.|
30| writableHighWatermark | number | Yes| No | High watermark for the data volume in the writable stream buffer. This value is not customizable currently. When you call [write()](#write), if the data volume in the buffer reaches this watermark, [write()](#write) will return **false**. The default value is 16 * 1024, in bytes.|
31| writable | boolean | Yes| No | Whether the writable stream is currently writable. The value **true** means that the stream is currently writable, and **false** means that the stream does not accept write operations.|
32| writableLength | number | Yes| No | Number of bytes to be written in the buffer of the writable stream.|
33| writableCorked | number | Yes | No| Count of cork states of the writable stream. If the value is greater than 0, the writable stream buffers all writes. If the value is **0**, buffering stops. You can call [cork()](#cork) to increment the count by one, call [uncork()](#uncork) to decrement the count by one, and call [end()](#end) to clear the count.|
34| writableEnded | boolean | Yes | No| Whether [end()](#end) has been called for the writable stream. This property does not specify whether the data has been flushed. The value **true** means that [end()](#end) has been called, and **false** means the opposite.|
35| writableFinished | boolean | Yes | No| Whether data in the writable stream has been flushed. The value **true** means that data in the stream has been flushed, and **false** means the opposite.|
36
37### constructor
38
39constructor()
40
41A constructor used to create a **Writable** object.
42
43**Atomic service API**: This API can be used in atomic services since API version 12.
44
45**System capability**: SystemCapability.Utils.Lang
46
47**Example**
48
49```ts
50let writableStream = new stream.Writable();
51```
52
53### write
54
55write(chunk?: string | Uint8Array, encoding?: string, callback?: Function): boolean
56
57Writes data to the buffer of the stream. This API uses an asynchronous callback to return the result.
58
59**Atomic service API**: This API can be used in atomic services since API version 12.
60
61**System capability**: SystemCapability.Utils.Lang
62
63**Parameters**
64
65| Name| Type  | Mandatory| Description                      |
66| ------ | ------ | ---- | -------------------------- |
67| chunk  | string \| Uint8Array | No| Data to write. It cannot be **null**, **undefined**, or an empty string.|
68| encoding  | string | No  | Encoding format. The default value is **'utf8'**. Currently, **'utf8'**, **'gb18030'**, **'gbk'**, and **'gb2312'** are supported.|
69| callback  | Function | No  | Callback used to return the result. It is not called by default.|
70
71**Return value**
72
73| Type  | Description                  |
74| ------ | ---------------------- |
75| boolean | Whether there is space in the buffer of the writable stream. The value **true** means that there is still space in the buffer. The value **false** means that the buffer is full, and you are not advised to continue writing data.|
76
77**Error codes**
78
79For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
80
81| ID| Error Message|
82| -------- | -------- |
83| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
84| 10200035 | The doWrite method has not been implemented. |
85| 10200036 | The stream has been ended. |
86| 10200037 | The callback is invoked multiple times consecutively. |
87
88**Example**
89
90```ts
91class TestWritable extends stream.Writable {
92  constructor() {
93    super();
94  }
95
96  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
97    console.info("Writable chunk is", chunk); // Writable chunk is test
98    callback();
99  }
100}
101
102let writableStream = new TestWritable();
103writableStream.write('test', 'utf8');
104```
105
106### end
107
108end(chunk?: string | Uint8Array, encoding?: string, callback?: Function): Writable
109
110Ends the writing process in a writable stream. This API uses an asynchronous callback to return the result.
111
112If the value of **writableCorked** is greater than 0, the value is set to **0** and the remaining data in the buffer is output.
113
114If the **chunk** parameter is passed, it is treated as the final data chunk and written using either the **write** or **doWrite** API, based on the current execution context.
115
116If **doWrite** is used for writing, the validity check of the **encoding** parameter depends on **doWrite**.
117
118If **end** is used alone (without **write**) and the **chunk** parameter is passed, the data is written through **doWrite**.
119
120**Atomic service API**: This API can be used in atomic services since API version 12.
121
122**System capability**: SystemCapability.Utils.Lang
123
124**Parameters**
125
126| Name| Type  | Mandatory| Description                      |
127| ------ | ------ | ---- | -------------------------- |
128| chunk  | string \| Uint8Array | No| Data to write. The default value is **undefined**.|
129| encoding  | string | No  | Encoding format. The default value is **'utf8'**. Currently, **'utf8'**, **'gb18030'**, **'gbk'**, and **'gb2312'** are supported.|
130| callback  | Function | No  | Callback used to return the result.|
131
132**Return value**
133
134| Type  | Description                  |
135| ------ | ---------------------- |
136| [Writable](#writable) | Current **Writable** object.|
137
138**Error codes**
139
140For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
141
142| ID| Error Message|
143| -------- | -------- |
144| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
145| 10200035 | The doWrite method has not been implemented. |
146
147**Example**
148
149```ts
150class TestWritable extends stream.Writable {
151  constructor() {
152    super();
153  }
154
155  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
156    console.info("Writable chunk is", chunk);
157    callback();
158  }
159/**
160 * Writable chunk is test
161 * Writable chunk is finish
162 * */
163}
164
165let writableStream = new TestWritable();
166writableStream.write('test', 'utf8');
167writableStream.end('finish', 'utf8', () => {
168  console.info("Writable is end"); // Writable is end
169});
170```
171
172### setDefaultEncoding
173
174setDefaultEncoding(encoding?: string): boolean
175
176Sets the default encoding format for the writable stream.
177
178**Atomic service API**: This API can be used in atomic services since API version 12.
179
180**System capability**: SystemCapability.Utils.Lang
181
182**Parameters**
183
184| Name| Type| Mandatory| Description|
185| -------- | -------- | -------- | -------- |
186| encoding | string | No| Default encoding format. The default value is **'utf8'**. Currently, **'utf8'**, **'gb18030'**, **'gbk'**, and **'gb2312'** are supported.|
187
188**Return value**
189
190| Type| Description|
191| -------- | -------- |
192| boolean | Operation result. The value **true** is returned if the setting is successful; otherwise, **false** is returned.|
193
194**Error codes**
195
196For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
197
198| ID| Error Message|
199| -------- | -------- |
200| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
201
202**Example**
203
204```ts
205class TestWritable extends stream.Writable {
206  constructor() {
207    super();
208  }
209
210  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
211    callback();
212  }
213}
214
215let writableStream = new TestWritable();
216let result = writableStream.setDefaultEncoding('utf8');
217console.info("Writable is result", result); // Writable is result true
218```
219
220### cork
221
222cork(): boolean
223
224Forces subsequent writes to be buffered. This API is called to optimize the performance of continuous write operations.
225
226After this API is called, the value of **writableCorked** is incremented by one. It is recommended that this API be used in pair with [uncork()](#uncork).
227
228**Atomic service API**: This API can be used in atomic services since API version 12.
229
230**System capability**: SystemCapability.Utils.Lang
231
232**Return value**
233
234| Type| Description|
235| -------- | -------- |
236| boolean | Operation result. The value **true** is returned if the corked status is successfully set; otherwise, **false** is returned.|
237
238**Example**
239
240```ts
241class TestWritable extends stream.Writable {
242  constructor() {
243    super();
244  }
245
246  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
247    callback();
248  }
249}
250
251let writableStream = new TestWritable();
252let result = writableStream.cork();
253console.info("Writable cork result", result); // Writable cork result true
254```
255
256### uncork
257
258uncork(): boolean
259
260Releases the cork state, flushing the buffered data and writing it to the target location.
261
262After this API is called, the value of **writableCorked** is decremented by one. If the value reaches **0**, the stream is no longer in the cork state. Otherwise, the stream is still in the cork state. It is recommended that this API be used in pair with [cork()](#cork).
263
264**Atomic service API**: This API can be used in atomic services since API version 12.
265
266**System capability**: SystemCapability.Utils.Lang
267
268**Return value**
269
270| Type| Description|
271| -------- | -------- |
272| boolean | Operation result. The value **true** is returned if the corked status is removed; otherwise, **false** is returned.|
273
274**Example**
275
276```ts
277class TestWritable extends stream.Writable {
278  constructor() {
279    super();
280  }
281
282  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
283    callback();
284  }
285}
286
287let writableStream = new TestWritable();
288writableStream.cork();
289writableStream.write('data1', 'utf8');
290writableStream.write('data2', 'utf8');
291writableStream.uncork();
292writableStream.end();
293writableStream.on('finish', () => {
294  console.info("all Data is End"); // all Data is End
295});
296```
297
298### on
299
300on(event: string, callback: Callback<emitter.EventData>): void
301
302Registers an event processing callback to listen for different events on the writable stream.
303
304**Atomic service API**: This API can be used in atomic services since API version 12.
305
306**System capability**: SystemCapability.Utils.Lang
307
308**Parameters**
309
310| Name| Type| Mandatory| Description|
311| -------- | -------- | -------- | -------- |
312| event    | string   | Yes| Type of the event. The following events are supported:| `'drain' `\|`'error'` \|  <br>\- **'close'**: triggered when the call of [end()](#end) is complete and the write operation ends.<br>\- **'drain'**: triggered when the data in the buffer of the writable stream is cleared.<br>\- **'error'**: triggered when an exception occurs in the writable stream.<br>\- **'finish'**: triggered when all data in the buffer is written to the target.|
313| callback | Callback\<[emitter.EventData](../apis-basic-services-kit/js-apis-emitter.md#eventdata)\> | Yes| Callback function used to return the event data.|
314
315**Error codes**
316
317For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
318
319| ID| Error Message|
320| -------- | -------- |
321| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
322
323**Example**
324
325```ts
326class TestWritable extends stream.Writable {
327  constructor() {
328    super();
329  }
330
331  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
332    callback(new Error());
333  }
334}
335
336let callbackCalled = false;
337let writable = new TestWritable();
338writable.on('error', () => {
339  console.info("Writable event test", callbackCalled.toString()); // Writable event test false
340});
341writable.write('hello', 'utf8', () => {
342});
343```
344
345### off
346
347off(event: string, callback?: Callback<emitter.EventData>): void
348
349Unregisters an event processing callback used to listen for different events on the writable stream.
350
351**Atomic service API**: This API can be used in atomic services since API version 12.
352
353**System capability**: SystemCapability.Utils.Lang
354
355**Parameters**
356
357| Name| Type| Mandatory| Description|
358| -------- | -------- | -------- | -------- |
359| event    | string   | Yes| Type of the event. The following events are supported:| `'drain' `\|`'error'` \|  <br>\- **'close'**: triggered when the call of [end()](#end) is complete and the write operation ends.<br>\- **'drain'**: triggered when the data in the buffer of the writable stream is cleared.<br>\- **'error'**: triggered when an exception occurs in the writable stream.<br>\- **'finish'**: triggered when all data in the buffer is written to the target.|
360| callback | Callback\<[emitter.EventData](../apis-basic-services-kit/js-apis-emitter.md#eventdata)\>   | No| Callback function.|
361
362**Error codes**
363
364For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
365
366| ID| Error Message|
367| -------- | -------- |
368| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
369
370**Example**
371
372```ts
373class TestWritable extends stream.Writable {
374  constructor() {
375    super();
376 }
377
378  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
379    callback();
380  }
381}
382
383let writableStream = new TestWritable();
384let testListenerCalled = false;
385let testListener = () => {
386  testListenerCalled = true;
387};
388writableStream.on('finish', testListener);
389writableStream.off('finish');
390writableStream.write('test');
391writableStream.end();
392setTimeout(() => {
393  console.info("Writable off test", testListenerCalled.toString()); // Writable off test false
394}, 0);
395```
396
397### doInitialize
398
399doInitialize(callback: Function): void
400
401You need to implement this API but do not call it directly. It is automatically called during the initialization of the writable stream. This API uses an asynchronous callback to return the result.
402
403**Atomic service API**: This API can be used in atomic services since API version 12.
404
405**System capability**: SystemCapability.Utils.Lang
406
407**Parameters**
408
409| Name   | Type    | Mandatory    | Description|
410| -------- | -------- | -------- | -------- |
411| callback | Function | Yes| Callback function.|
412
413**Error codes**
414
415For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
416
417| ID| Error Message|
418| -------- | -------- |
419| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
420
421**Example**
422
423```ts
424class MyWritable extends stream.Writable {
425  doInitialize(callback: Function) {
426    super.doInitialize(callback);
427    console.info("Writable doInitialize"); // Writable doInitialize
428  }
429
430  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
431    super.doWrite(chunk, encoding, callback);
432  }
433}
434
435new MyWritable();
436```
437
438### doWrite
439
440doWrite(chunk: string | Uint8Array, encoding: string, callback: Function): void
441
442A data write API. You need to implement this API but do not call it directly. This API is automatically called when data is written. This API uses an asynchronous callback to return the result.
443
444**Atomic service API**: This API can be used in atomic services since API version 12.
445
446**System capability**: SystemCapability.Utils.Lang
447
448**Parameters**
449
450| Name| Type  | Mandatory| Description                      |
451| ------ | ------ | ---- | -------------------------- |
452| chunk  | string \| Uint8Array | Yes| Data to write.|
453| encoding  | string | Yes  | Encoding format. Currently, **'utf8'**, **'gb18030'**, **'gbk'**, and **'gb2312'** are supported.|
454| callback  | Function | Yes  | Callback function.|
455
456**Error codes**
457
458For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
459
460| ID| Error Message|
461| -------- | -------- |
462| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
463
464**Example**
465
466```ts
467class TestWritable extends stream.Writable {
468  constructor() {
469    super();
470  }
471
472  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
473    console.info("Writable chunk is", chunk); // Writable chunk is data
474    callback();
475  }
476}
477
478let writableStream = new TestWritable();
479writableStream.write('data', 'utf8');
480```
481
482### doWritev
483
484doWritev(chunks: string[] | Uint8Array[], callback: Function): void
485
486A batch data write API. You need to implement this API but do not call it directly. This API is automatically called when data is written. This API uses an asynchronous callback to return the result.
487
488**Atomic service API**: This API can be used in atomic services since API version 12.
489
490**System capability**: SystemCapability.Utils.Lang
491
492**Parameters**
493
494| Name| Type| Mandatory| Description|
495| -------- | -------- | -------- | -------- |
496| chunks    | string[] \|  Uint8Array[] | Yes| Data arrays to write in batches.|
497| callback  | Function | Yes| Callback function.|
498
499**Error codes**
500
501For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
502
503| ID| Error Message|
504| -------- | -------- |
505| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
506
507**Example**
508
509```ts
510class TestWritable extends stream.Writable {
511  constructor() {
512    super();
513  }
514
515  doWritev(chunks: string[] | Uint8Array[], callback: Function) {
516    console.info("Writable chunk", chunks);
517    callback();
518  }
519/**
520 * Writable chunk data1
521 * Writable chunk data2
522* */
523}
524
525let writableStream = new TestWritable();
526writableStream.write('data1', 'utf8');
527writableStream.write('data2', 'utf8');
528writableStream.uncork();
529writableStream.end();
530```
531
532## ReadableOptions
533
534Describes the options used in the **Readable** constructor.
535
536**Atomic service API**: This API can be used in atomic services since API version 12.
537
538**System capability**: SystemCapability.Utils.Lang
539
540| Name| Type| Mandatory| Description|
541| ---- | -------- | ---- | -------------- |
542| encoding | string  | No| Encoding format. If an invalid string is input, an exception is thrown in the **Readable** constructor.<br>The following formats are supported: utf-8, UTF-8, GBK, GB2312, gb2312, GB18030, gb18030, ibm866, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-8-i, iso-8859-10, iso-8859-13, iso-8859-14, iso-8859-15, koi8-r, koi8-u, macintosh, windows-874, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, gbk, big5, euc-jp, iso-2022-jp, shift_jis, euc-kr, x-mac-cyrillic, utf-16be, and utf-16le.<br>The default value is **'utf-8'**.|
543
544## Readable
545
546Stream from which data can be read. A readable stream is used to read data from a source, such as a file or a network socket.
547
548### Properties
549
550**Atomic service API**: This API can be used in atomic services since API version 12.
551
552**System capability**: SystemCapability.Utils.Lang
553
554| Name   | Type     | Read-Only| Optional | Description       |
555| ------- | -------- | ------ | ------ | ----------- |
556| readableObjectMode  | boolean   | Yes  | No| Whether the readable stream works in object mode. The value **true** means that the stream is configured in object mode, and **false** means the opposite. Currently, only raw data (string and Uint8Array) is supported, and the return value is **false**.|
557| readable | boolean | Yes| No | Whether the readable stream is currently readable. The value **true** means that the stream is currently readable, and **false** means that no data is available to read from the stream.|
558| readableHighWatermark | number | Yes| No | Maximum amount of data that can be stored in the buffer. The default value is 16 * 1024, in bytes.|
559| readableFlowing | boolean \| null | Yes| No | Whether the readable stream is flowing. The value **true** means that the stream is flowing, and **false** means the opposite. The default value is **true**.|
560| readableLength | number | Yes| No | Number of bytes in the buffer.|
561| readableEncoding | string \| null | Yes| No | Encoding format. The default value is **'utf8'**. Currently, **'utf8'**, **'gb18030'**, **'gbk'**, and **'gb2312'** are supported.|
562| readableEnded | boolean | Yes | No| Whether the readable stream ends. The value **true** means that the stream has no more data to read, and **false** means the opposite.|
563
564### constructor
565
566constructor()
567
568A constructor used to create a **Readable** object.
569
570**Atomic service API**: This API can be used in atomic services since API version 12.
571
572**System capability**: SystemCapability.Utils.Lang
573
574**Example**
575
576```ts
577let readableStream = new stream.Readable();
578```
579
580### constructor
581
582constructor(options: ReadableOptions)
583
584A constructor used to create a **Readable** object.
585
586**Atomic service API**: This API can be used in atomic services since API version 12.
587
588**System capability**: SystemCapability.Utils.Lang
589
590**Parameters**
591
592| Name | Type| Mandatory| Description|
593| ------ | -------- | -------- | -------- |
594| options   | [ReadableOptions](#readableoptions)   | Yes| Options in the **Readable** constructor.|
595
596**Error codes**
597
598For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
599
600| ID| Error Message|
601| -------- | -------- |
602| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
603
604**Example**
605
606```ts
607let option : stream.ReadableOptions = {
608  encoding : 'utf-8'
609};
610let readableStream = new stream.Readable(option);
611```
612
613### read
614
615read(size?: number): string | null
616
617Reads data from the buffer of the readable stream and returns the read data. If no data is read, **null** is returned.
618
619**Atomic service API**: This API can be used in atomic services since API version 12.
620
621**System capability**: SystemCapability.Utils.Lang
622
623**Parameters**
624
625| Name | Type| Mandatory| Description|
626| ------ | -------- | -------- | -------- |
627| size   | number   | No| Number of bytes to read. The default value is **undefined**.|
628
629**Return value**
630
631| Type  | Description                  |
632| ------ | ---------------------- |
633| string \| null | Data read from the readable stream.|
634
635**Error codes**
636
637For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
638
639| ID| Error Message|
640| -------- | -------- |
641| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
642| 10200038 | The doRead method has not been implemented. |
643
644**Example**
645
646```ts
647class TestReadable extends stream.Readable {
648  constructor() {
649    super();
650  }
651
652  doRead(size: number) {
653  }
654}
655
656let readableStream = new TestReadable();
657readableStream.push('test');
658readableStream.pause();
659let dataChunk = readableStream.read();
660console.info('Readable data is', dataChunk); // Readable data is test
661```
662
663### resume
664
665resume(): Readable
666
667Resumes an explicitly paused readable stream. You can use **isPaused** to check whether the stream is paused.
668
669**Atomic service API**: This API can be used in atomic services since API version 12.
670
671**System capability**: SystemCapability.Utils.Lang
672
673**Return value**
674
675| Type  | Description                  |
676| ------ | ---------------------- |
677| [Readable](#readable) | Current **Readable** object.|
678
679**Example**
680
681```ts
682class TestReadable extends stream.Readable {
683  constructor() {
684    super();
685  }
686
687  doRead(size: number) {
688  }
689}
690
691let readableStream = new TestReadable();
692readableStream.resume();
693console.info("Readable test resume", !readableStream.isPaused()); // After a successful switching, the log "Readable test resume true" is displayed.
694```
695
696### pause
697
698pause(): Readable
699
700Pauses the readable stream in flowing mode. You can use **isPaused** to check whether the stream is paused.
701
702**Atomic service API**: This API can be used in atomic services since API version 12.
703
704**System capability**: SystemCapability.Utils.Lang
705
706**Return value**
707
708| Type  | Description                  |
709| ------ | ---------------------- |
710| [Readable](#readable) | Current **Readable** object.|
711
712**Example**
713
714```ts
715class TestReadable extends stream.Readable {
716  constructor() {
717    super();
718  }
719
720  doRead(size: number) {
721  }
722}
723
724let readableStream = new TestReadable();
725readableStream.pause();
726console.info("Readable test pause", readableStream.isPaused()); // Readable test pause true
727```
728
729### setEncoding
730
731setEncoding(encoding?: string): boolean
732
733Sets an encoding format for the readable stream.
734If the buffer contains data, setting the encoding format is not allowed, and **false** is returned.
735
736**Atomic service API**: This API can be used in atomic services since API version 12.
737
738**System capability**: SystemCapability.Utils.Lang
739
740**Parameters**
741
742| Name| Type| Mandatory| Description|
743| -------- | -------- | -------- | -------- |
744| encoding | string | No| Encoding format. The default value is **'utf8'**. Currently, **'utf8'**, **'gb18030'**, **'gbk'**, and **'gb2312'** are supported.|
745
746**Return value**
747
748| Type| Description|
749| -------- | -------- |
750| boolean | Operation result. The value **true** is returned if the setting is successful; otherwise, **false** is returned.|
751
752**Error codes**
753
754For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
755
756| ID| Error Message|
757| -------- | -------- |
758| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
759
760**Example**
761
762```ts
763class TestReadable extends stream.Readable {
764  constructor() {
765    super();
766  }
767
768  doRead(size: number) {
769  }
770}
771
772let readableStream = new TestReadable();
773let result = readableStream.setEncoding('utf8');
774console.info("Readable result", result); // Readable result true
775```
776
777### isPaused
778
779isPaused(): boolean
780
781Checks whether the readable stream is paused. The stream is paused after [pause()](#pause) is called and resumes from the paused state after [resume()](#resume) is called.
782
783**Atomic service API**: This API can be used in atomic services since API version 12.
784
785**System capability**: SystemCapability.Utils.Lang
786
787**Return value**
788
789| Type| Description|
790| -------- | -------- |
791| boolean | Check result. The value **true** is returned if the stream is paused; otherwise, **false** is returned.|
792
793**Example**
794
795```ts
796class TestReadable extends stream.Readable {
797  constructor() {
798    super();
799  }
800
801  doRead(size: number) {
802  }
803}
804
805let readableStream = new TestReadable();
806console.info("Readable isPaused", readableStream.isPaused()); // Readable isPaused false
807readableStream.pause();
808console.info("Readable isPaused", readableStream.isPaused()); // Readable isPaused true
809```
810
811### pipe
812
813pipe(destination: Writable, options?: Object): Writable
814
815Attaches a writable stream to the readable stream to implement automatic data transmission.
816
817**Atomic service API**: This API can be used in atomic services since API version 12.
818
819**System capability**: SystemCapability.Utils.Lang
820
821**Parameters**
822
823| Name| Type| Mandatory| Description|
824| -------- | -------- | -------- | -------- |
825| destination | [Writable](#writable) | Yes| Writable stream that receives data.|
826| options     | Object | No| Reserved.|
827
828**Return value**
829
830| Type| Description|
831| -------- | -------- |
832| [Writable](#writable) | Current **Writable** object.|
833
834**Error codes**
835
836For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
837
838| ID| Error Message|
839| -------- | -------- |
840| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
841
842**Example**
843
844```ts
845class TestReadable extends stream.Readable {
846  constructor() {
847    super();
848  }
849
850  doRead(size: number) {
851    readable.push('test');
852    readable.push(null);
853  }
854}
855
856class TestWritable extends stream.Writable {
857  constructor() {
858    super();
859  }
860
861  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
862    console.info("Readable test pipe", chunk); // Readable test pipe test
863    callback();
864  }
865}
866
867let readable = new TestReadable();
868let writable = new TestWritable();
869readable.pipe(writable);
870```
871
872### unpipe
873
874unpipe(destination?: Writable): Readable
875
876Detaches a writable stream previously attached to the readable stream.
877
878**Atomic service API**: This API can be used in atomic services since API version 12.
879
880**System capability**: SystemCapability.Utils.Lang
881
882**Parameters**
883
884| Name| Type| Mandatory| Description|
885| -------- | -------- | -------- | -------- |
886| destination | [Writable](#writable) | No| Writable stream to detach. The default value is **undefined**.|
887
888**Return value**
889
890| Type| Description|
891| -------- | -------- |
892| [Readable](#readable) | Current **Readable** object.|
893
894**Error codes**
895
896For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
897
898| ID| Error Message|
899| -------- | -------- |
900| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
901
902**Example**
903
904```ts
905class TestReadable extends stream.Readable {
906  constructor() {
907    super();
908  }
909
910  doRead(size: number) {
911    readable.push('test');
912    readable.push(null);
913  }
914}
915
916class TestWritable extends stream.Writable {
917  constructor() {
918    super();
919  }
920
921  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
922    callback();
923  }
924}
925
926let readable = new TestReadable();
927let writable = new TestWritable();
928readable.pipe(writable);
929readable.unpipe(writable);
930readable.on('data', () => {
931  console.info("Readable test unpipe data event called");
932});
933// After successful detaching, the data event is not triggered and "Readable test unpipe data event called" is not printed.
934```
935
936### on
937
938on(event: string, callback: Callback<emitter.EventData>): void
939
940Registers an event processing callback to listen for different events on the readable stream.
941
942**Atomic service API**: This API can be used in atomic services since API version 12.
943
944**System capability**: SystemCapability.Utils.Lang
945
946**Parameters**
947
948| Name| Type| Mandatory| Description|
949| -------- | -------- | -------- | -------- |
950| event    | string   | Yes| Type of the event. The following events are supported:| `'data' `\|`'end'` \| `'error'`\|`'readable'`\|`'pause'`\| <br>\- **'close'**: triggered when [push()](#push) is called, with **null** passed in.<br>\- **'data'**: triggered when a data chunk is transferred to a consumer.<br>\- **'end'**: triggered when [push()](#push) is called, with **null** passed in.<br>\- **'error'**: triggered when an exception occurs in the stream.<br>\- **'readable'**: triggered when there is data available to be read from the stream.<br>\- **'pause'**: triggered when [pause()](#pause) is called.<br>\- **'resume'**: triggered when [resume()](#resume) is called.|
951| callback | Callback\<[emitter.EventData](../apis-basic-services-kit/js-apis-emitter.md#eventdata)\> | Yes| Callback function used to return the event data.|
952
953**Error codes**
954
955For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
956
957| ID| Error Message|
958| -------- | -------- |
959| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
960
961**Example**
962
963```ts
964class TestReadable extends stream.Readable {
965  constructor() {
966    super();
967  }
968
969  doRead(size: number) {
970    throw new Error('Simulated error');
971  }
972}
973
974let readable = new TestReadable();
975readable.push('test');
976readable.on('error', () => {
977  console.info("error event called"); // error event called
978});
979```
980
981### off
982
983off(event: string, callback?: Callback<emitter.EventData>): void
984
985Unregisters an event processing callback used to listen for different events on the readable stream.
986
987**Atomic service API**: This API can be used in atomic services since API version 12.
988
989**System capability**: SystemCapability.Utils.Lang
990
991**Parameters**
992
993| Name| Type| Mandatory| Description|
994| -------- | -------- | -------- | -------- |
995| event    | string   | Yes| Type of the event. The following events are supported:| `'data' `\|`'end'` \| `'error'`\|`'readable'`\|`'pause'`\| <br>\- **'close'**: triggered when [push()](#push) is called, with **null** passed in.<br>\- **'data'**: triggered when a data chunk is transferred to a consumer.<br>\- **'end'**: triggered when [push()](#push) is called, with **null** passed in.<br>\- **'error'**: triggered when an exception occurs in the stream.<br>\- **'readable'**: triggered when there is data available to be read from the stream.<br>\- **'pause'**: triggered when [pause()](#pause) is called.<br>\- **'resume'**: triggered when [resume()](#resume) is called.|
996| callback | Callback\<[emitter.EventData](../apis-basic-services-kit/js-apis-emitter.md#eventdata)\>   | No| Callback function.|
997
998**Error codes**
999
1000For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1001
1002| ID| Error Message|
1003| -------- | -------- |
1004| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
1005
1006**Example**
1007
1008```ts
1009class TestReadable extends stream.Readable {
1010  constructor() {
1011    super();
1012  }
1013
1014  doRead(size: number) {
1015  }
1016}
1017
1018let readable = new TestReadable();
1019
1020function read() {
1021  console.info("read() called");
1022}
1023
1024readable.setEncoding('utf8');
1025readable.on('readable', read);
1026readable.off('readable');
1027readable.push('test');
1028// After off is used to unregister the listening of the readable stream events, the read function is not called and "read() called" is not printed.
1029```
1030
1031### doInitialize
1032
1033doInitialize(callback: Function): void
1034
1035You need to implement this API. It is called when the readable stream calls [on](#on-1) for the first time. This API uses an asynchronous callback to return the result.
1036
1037**Atomic service API**: This API can be used in atomic services since API version 12.
1038
1039**System capability**: SystemCapability.Utils.Lang
1040
1041**Parameters**
1042
1043| Name   | Type    | Mandatory    | Description|
1044| -------- | -------- | -------- | -------- |
1045| callback | Function | Yes| Callback function.|
1046
1047**Error codes**
1048
1049For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1050
1051| ID| Error Message|
1052| -------- | -------- |
1053| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1054
1055**Example**
1056
1057```ts
1058class MyReadable extends stream.Readable {
1059  doInitialize(callback: Function) {
1060    super.doInitialize(callback);
1061    console.info("Readable doInitialize"); // Readable doInitialize
1062}
1063
1064  doRead(size: number) {
1065  }
1066}
1067
1068let myReadable = new MyReadable();
1069myReadable.on('data', () => {
1070});
1071```
1072
1073### doRead
1074
1075doRead(size: number): void
1076
1077A data read API that needs to be implemented in child classes.
1078
1079**Atomic service API**: This API can be used in atomic services since API version 12.
1080
1081**System capability**: SystemCapability.Utils.Lang
1082
1083**Parameters**
1084
1085| Name   | Type    | Mandatory    | Description|
1086| -------- | -------- | -------- | -------- |
1087| size | number | Yes| Number of bytes to read. Value range: 0 <= size <= Number.MAX_VALUE|
1088
1089**Error codes**
1090
1091For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1092
1093| ID| Error Message|
1094| -------- | -------- |
1095| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1096
1097**Example**
1098
1099```ts
1100class TestReadable extends stream.Readable {
1101  constructor() {
1102    super();
1103  }
1104
1105  doRead(size: number) {
1106    console.info("doRead called"); // doRead called
1107  }
1108}
1109
1110let readable = new TestReadable();
1111readable.on('data', () => {
1112});
1113```
1114
1115### push
1116
1117push(chunk:  Uint8Array | string | null, encoding?: string): boolean
1118
1119Pushes data into the buffer of the readable stream.
1120
1121**Atomic service API**: This API can be used in atomic services since API version 12.
1122
1123**System capability**: SystemCapability.Utils.Lang
1124
1125**Parameters**
1126
1127| Name   | Type    | Mandatory    | Description|
1128| -------- | -------- | -------- | -------- |
1129| chunk | Uint8Array \| string  \| null | Yes| Data to read.|
1130| encoding | string | No| Encoding format. The default value is **'utf8'**. Currently, **'utf8'**, **'gb18030'**, **'gbk'**, and **'gb2312'** are supported.|
1131
1132**Return value**
1133
1134| Type| Description|
1135| -------- | -------- |
1136| boolean | Whether there is space in the buffer of the readable stream. The value **true** means that there is still space in the buffer, and **false** means that the buffer is full. If **null** is passed, **false** is always returned, indicating that no data chunk is available for pushing.|
1137
1138**Error codes**
1139
1140For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1141
1142| ID| Error Message|
1143| -------- | -------- |
1144| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
1145
1146**Example**
1147
1148```ts
1149class TestReadable extends stream.Readable {
1150  constructor() {
1151    super();
1152  }
1153
1154  doRead(size: number) {
1155  }
1156}
1157
1158let readable = new TestReadable();
1159let testData = 'Hello world';
1160readable.push(testData);
1161console.info("Readable push test", readable.readableLength); // Readable push test 11
1162```
1163
1164## Duplex
1165
1166A stream that is both readable and writable. A duplex stream allows data to be transmitted in two directions, that is, data can be read and written.
1167The **Duplex** class inherits from [Readable](#readable) and supports all the APIs in **Readable**.
1168
1169### Properties
1170
1171**Atomic service API**: This API can be used in atomic services since API version 12.
1172
1173**System capability**: SystemCapability.Utils.Lang
1174
1175| Name   | Type     | Read-Only| Optional | Description       |
1176| ------- | -------- | ------ | ------ | ----------- |
1177| writableObjectMode  | boolean   | Yes  | No| Whether the writable side of the duplex stream works in object mode. The value **true** means that the writable side of the stream is configured in object mode, and **false** means the opposite. Currently, only raw data (string and Uint8Array) is supported, and the return value is **false**.|
1178| writableHighWatermark | number | Yes| No | High watermark for the data volume in the buffer of the duplex stream in write mode. This value is not customizable currently. When you call [write()](#write-1), if the data volume in the buffer reaches this watermark, [write()](#write-1) will return **false**. The default value is 16 * 1024, in bytes.|
1179| writable | boolean | Yes| No | Whether the duplex stream is currently writable. The value **true** means that the stream is currently writable, and **false** means that the stream does not accept write operations.|
1180| writableLength | number | Yes| No | Number of bytes to be written in the buffer of the duplex stream.|
1181| writableCorked | number | Yes | No| Count of cork states of the duplex stream. If the value is greater than 0, the duplex stream buffers all writes. If the value is **0**, buffering stops. You can call [cork()](#cork-1) to increment the count by one, call [uncork()](#uncork-1) to decrement the count by one, and call [end()](#end-1) to clear the count.|
1182| writableEnded | boolean | Yes | No| Whether [end()](#end-1) has been called for the duplex stream. This property does not specify whether the data has been flushed. The value **true** means that [end()](#end-1) has been called, and **false** means the opposite.|
1183| writableFinished | boolean | Yes | No| Whether data in the duplex stream has been flushed. The value **true** means that data in the stream has been flushed, and **false** means the opposite.|
1184
1185### constructor
1186
1187constructor()
1188
1189A constructor used to create a **Duplex** object.
1190
1191**Atomic service API**: This API can be used in atomic services since API version 12.
1192
1193**System capability**: SystemCapability.Utils.Lang
1194
1195**Example**
1196
1197```ts
1198let duplex = new stream.Duplex();
1199```
1200
1201### write
1202
1203write(chunk?: string | Uint8Array, encoding?: string, callback?: Function): boolean
1204
1205Writes data to the buffer of the stream. This API uses an asynchronous callback to return the result.
1206
1207**Atomic service API**: This API can be used in atomic services since API version 12.
1208
1209**System capability**: SystemCapability.Utils.Lang
1210
1211**Parameters**
1212
1213| Name| Type  | Mandatory| Description                      |
1214| ------ | ------ | ---- | -------------------------- |
1215| chunk  | string \| Uint8Array | No| Data to write. It cannot be **null**, **undefined**, or an empty string.|
1216| encoding  | string | No  | Encoding format. The default value is **'utf8'**. Currently, **'utf8'**, **'gb18030'**, **'gbk'**, and **'gb2312'** are supported.|
1217| callback  | Function | No  | Callback used to return the result. It is not called by default.|
1218
1219**Return value**
1220
1221| Type  | Description                  |
1222| ------ | ---------------------- |
1223| boolean | Whether there is space in the buffer of the writable stream. The value **true** means that there is still space in the buffer. The value **false** means that the buffer is full, and you are not advised to continue writing data.|
1224
1225**Error codes**
1226
1227For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1228
1229| ID| Error Message|
1230| -------- | -------- |
1231| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1232| 10200036 | The stream has been ended. |
1233| 10200037 | The callback is invoked multiple times consecutively. |
1234| 10200039 | The doTransform method has not been implemented for a class that inherits from Transform. |
1235
1236**Example**
1237
1238```ts
1239class TestDuplex extends stream.Duplex {
1240  constructor() {
1241    super();
1242  }
1243
1244  doRead(size: number) {
1245  }
1246
1247  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
1248    console.info("duplexStream chunk is", chunk); // duplexStream chunk is test
1249    callback();
1250  }
1251}
1252
1253let duplexStream = new TestDuplex();
1254let result = duplexStream.write('test', 'utf8');
1255console.info("duplexStream result", result); // duplexStream result true
1256```
1257
1258### end
1259
1260end(chunk?: string | Uint8Array, encoding?: string, callback?: Function): Writable
1261
1262Ends the writing process in a duplex stream. This API uses an asynchronous callback to return the result.
1263
1264If the value of **writableCorked** is greater than 0, the value is set to **0** and the remaining data in the buffer is output.
1265
1266If the **chunk** parameter is passed, it is treated as the final data chunk and written using either the **write** or **doWrite** API, based on the current execution context.
1267
1268If **doWrite** is used for writing, the validity check of the **encoding** parameter depends on **doWrite**.
1269
1270If **end** is used alone (without **write**) and the **chunk** parameter is passed, the data is written through **doWrite**.
1271
1272**Atomic service API**: This API can be used in atomic services since API version 12.
1273
1274**System capability**: SystemCapability.Utils.Lang
1275
1276**Parameters**
1277
1278| Name| Type  | Mandatory| Description                      |
1279| ------ | ------ | ---- | -------------------------- |
1280| chunk  | string \| Uint8Array | No| Data to write. The default value is **undefined**.|
1281| encoding  | string | No  | Encoding format. The default value is **'utf8'**. Currently, **'utf8'**, **'gb18030'**, **'gbk'**, and **'gb2312'** are supported.|
1282| callback  | Function | No  | Callback used to return the result. It is not called by default.|
1283
1284**Return value**
1285
1286| Type  | Description                  |
1287| ------ | ---------------------- |
1288| [Writable](#writable) | Current **Duplex** object.|
1289
1290**Error codes**
1291
1292For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
1293
1294| ID| Error Message|
1295| -------- | -------- |
1296| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1297| 10200039 | The doTransform method has not been implemented for a class that inherits from Transform. |
1298
1299**Example**
1300
1301```ts
1302class TestDuplex extends stream.Duplex {
1303  constructor() {
1304    super();
1305  }
1306
1307  doRead(size: number) {
1308  }
1309
1310  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
1311  console.info("Duplex chunk is", chunk); // Duplex chunk is test
1312  callback();
1313  }
1314}
1315
1316let duplexStream = new TestDuplex();
1317duplexStream.end('test', 'utf8', () => {
1318  console.info("Duplex is end"); // Duplex is end
1319});
1320```
1321
1322### setDefaultEncoding
1323
1324setDefaultEncoding(encoding?: string): boolean
1325
1326Sets the default encoding format for the duplex stream so that characters can be correctly parsed when data is read.
1327
1328**Atomic service API**: This API can be used in atomic services since API version 12.
1329
1330**System capability**: SystemCapability.Utils.Lang
1331
1332**Parameters**
1333
1334| Name| Type| Mandatory| Description|
1335| -------- | -------- | -------- | -------- |
1336| encoding | string | No| Encoding format. The default value is **'utf8'**. Currently, **'utf8'**, **'gb18030'**, **'gbk'**, and **'gb2312'** are supported.|
1337
1338**Return value**
1339
1340| Type| Description|
1341| -------- | -------- |
1342| boolean | Operation result. The value **true** is returned if the setting is successful; otherwise, **false** is returned.|
1343
1344**Error codes**
1345
1346For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1347
1348| ID| Error Message|
1349| -------- | -------- |
1350| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1351
1352**Example**
1353
1354```ts
1355class TestDuplex extends stream.Duplex {
1356  constructor() {
1357    super();
1358  }
1359
1360  doRead(size: number) {
1361  }
1362
1363  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
1364    callback();
1365  }
1366}
1367
1368let duplexStream = new TestDuplex();
1369let result = duplexStream.setDefaultEncoding('utf8');
1370console.info("duplexStream is result", result); // duplexStream is result true
1371```
1372
1373### cork
1374
1375cork(): boolean
1376
1377Forces all written data to be buffered in memory. This API is called to optimize the performance of continuous write operations.
1378
1379After this API is called, the value of **writableCorked** is incremented by one. It is recommended that this API be used in pair with [uncork()](#uncork-1).
1380
1381**Atomic service API**: This API can be used in atomic services since API version 12.
1382
1383**System capability**: SystemCapability.Utils.Lang
1384
1385**Return value**
1386
1387| Type| Description|
1388| -------- | -------- |
1389| boolean | Operation result. The value **true** is returned if the corked status is successfully set; otherwise, **false** is returned.|
1390
1391**Example**
1392
1393```ts
1394let duplexStream = new stream.Duplex();
1395let result = duplexStream.cork();
1396console.info("duplexStream cork result", result); // duplexStream cork result true
1397```
1398
1399### uncork
1400
1401uncork(): boolean
1402
1403Flushes all data buffered, and writes the data to the target.
1404
1405After this API is called, the value of **writableCorked** is decremented by one. If the value reaches **0**, the stream is no longer in the cork state. Otherwise, the stream is still in the cork state. It is recommended that this API be used in pair with [cork()](#cork-1).
1406
1407**Atomic service API**: This API can be used in atomic services since API version 12.
1408
1409**System capability**: SystemCapability.Utils.Lang
1410
1411**Return value**
1412
1413| Type| Description|
1414| -------- | -------- |
1415| boolean | Operation result. The value **true** is returned if the corked status is removed; otherwise, **false** is returned.|
1416
1417**Example**
1418
1419```ts
1420class TestDuplex extends stream.Duplex {
1421  constructor() {
1422    super();
1423  }
1424
1425  doRead(size: number) {
1426  }
1427
1428  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
1429    dataWritten += chunk;
1430    callback();
1431  }
1432}
1433
1434let dataWritten = '';
1435let duplexStream = new TestDuplex();
1436duplexStream.cork();
1437duplexStream.write('a');
1438duplexStream.write('b');
1439duplexStream.uncork();
1440console.info("Duplex test uncork", dataWritten); // Duplex test uncork ab
1441```
1442
1443### doWrite
1444
1445doWrite(chunk: string | Uint8Array, encoding: string, callback: Function): void
1446
1447A data write API. You need to implement this API but do not call it directly. This API is automatically called when data is written. This API uses an asynchronous callback to return the result.
1448
1449**Atomic service API**: This API can be used in atomic services since API version 12.
1450
1451**System capability**: SystemCapability.Utils.Lang
1452
1453**Parameters**
1454
1455| Name| Type  | Mandatory| Description                      |
1456| ------ | ------ | ---- | -------------------------- |
1457| chunk  | string \| Uint8Array | Yes| Data to write.|
1458| encoding  | string | Yes  | Encoding format. Currently, **'utf8'**, **'gb18030'**, **'gbk'**, and **'gb2312'** are supported.|
1459| callback  | Function | Yes  | Callback function.|
1460
1461**Error codes**
1462
1463For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1464
1465| ID| Error Message|
1466| -------- | -------- |
1467| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1468
1469**Example**
1470
1471```ts
1472class TestDuplex extends stream.Duplex {
1473  constructor() {
1474    super();
1475  }
1476
1477  doRead(size: number) {
1478  }
1479
1480  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
1481    console.info("duplexStream chunk is", chunk); // duplexStream chunk is data
1482    callback();
1483  }
1484}
1485
1486let duplexStream = new TestDuplex();
1487duplexStream.write('data', 'utf8');
1488```
1489
1490### doWritev
1491
1492doWritev(chunks: string[] | Uint8Array[], callback: Function): void
1493
1494A batch data write API. You need to implement this API but do not call it directly. This API is automatically called when data is written. This API uses an asynchronous callback to return the result.
1495
1496**Atomic service API**: This API can be used in atomic services since API version 12.
1497
1498**System capability**: SystemCapability.Utils.Lang
1499
1500**Parameters**
1501
1502| Name| Type| Mandatory| Description|
1503| -------- | -------- | -------- | -------- |
1504| chunks    | string[] \| Uint8Array[] | Yes| Data arrays to write in batches.|
1505| callback  | Function | Yes| Callback function.|
1506
1507**Error codes**
1508
1509For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1510
1511| ID| Error Message|
1512| -------- | -------- |
1513| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1514
1515**Example**
1516
1517```ts
1518class TestDuplex extends stream.Duplex {
1519  constructor() {
1520    super();
1521  }
1522
1523  doRead(size: number) {
1524  }
1525
1526  doWrite(chunk: string | Uint8Array, encoding: string, callback: Function) {
1527    callback();
1528  }
1529
1530  doWritev(chunks: string[] | Uint8Array[], callback: Function) {
1531    console.info("duplexStream chunk", chunks[0]); // duplexStream chunk data1
1532    callback();
1533  }
1534}
1535
1536let duplexStream = new TestDuplex();
1537duplexStream.cork();
1538duplexStream.write('data1', 'utf8');
1539duplexStream.write('data2', 'utf8');
1540duplexStream.uncork();
1541duplexStream.end();
1542```
1543
1544## Transform
1545
1546A special duplex stream that supports data conversion and result output. The **Transform** class inherits from [Duplex](#duplex) and supports all the APIs in **Duplex**.
1547
1548### constructor
1549
1550constructor()
1551
1552A constructor used to create a **Transform** object.
1553
1554**Atomic service API**: This API can be used in atomic services since API version 12.
1555
1556**System capability**: SystemCapability.Utils.Lang
1557
1558**Example**
1559
1560```ts
1561let transform = new stream.Transform();
1562```
1563
1564### doTransform
1565
1566doTransform(chunk: string, encoding: string, callback: Function): void
1567
1568Converts or processes input data chunks and uses a callback to notify that the processing is complete.
1569
1570**Atomic service API**: This API can be used in atomic services since API version 12.
1571
1572**System capability**: SystemCapability.Utils.Lang
1573
1574**Parameters**
1575
1576| Name   | Type    | Mandatory    | Description|
1577| -------- | -------- | -------- | -------- |
1578| chunk  | string | Yes| Data to write.|
1579| encoding  | string | Yes  | Encoding format. Currently, **'utf8'**, **'gb18030'**, **'gbk'**, and **'gb2312'** are supported.|
1580| callback  | Function | Yes  | Callback function.|
1581
1582**Error codes**
1583
1584For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1585
1586| ID| Error Message|
1587| -------- | -------- |
1588| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1589
1590**Example**
1591
1592```ts
1593class TestTransform extends stream.Transform {
1594  constructor() {
1595    super();
1596  }
1597
1598  doTransform(chunk: string, encoding: string, callback: Function) {
1599    let stringChunk = chunk.toString().toUpperCase();
1600    console.info("Transform test doTransform", stringChunk); // Transform test doTransform HELLO
1601    tr.push(stringChunk);
1602    callback();
1603  }
1604}
1605
1606let tr = new TestTransform();
1607tr.write("hello");
1608```
1609
1610### doFlush
1611
1612doFlush(callback: Function): void
1613
1614Called at the end of the stream to process the remaining data. This API uses an asynchronous callback to return the result.
1615
1616**Atomic service API**: This API can be used in atomic services since API version 12.
1617
1618**System capability**: SystemCapability.Utils.Lang
1619
1620**Parameters**
1621
1622| Name   | Type    | Mandatory    | Description|
1623| -------- | -------- | -------- | -------- |
1624| callback  | Function | Yes  | Callback function.|
1625
1626**Error codes**
1627
1628For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1629
1630| ID| Error Message|
1631| -------- | -------- |
1632| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
1633
1634**Example**
1635
1636```ts
1637class TestTransform extends stream.Transform {
1638  constructor() {
1639    super();
1640  }
1641
1642  doTransform(chunk: string, encoding: string, callback: Function) {
1643    callback();
1644  }
1645
1646  doFlush(callback: Function) {
1647    callback(null, 'test');
1648  }
1649}
1650
1651let transform = new TestTransform();
1652transform.end('my test');
1653transform.on('data', (data) => {
1654  console.info("data is", data.data); // data is test
1655});
1656```
1657