js-apis-file-fs.md 155.7 KB
Newer Older
A
Annie_wang 已提交
1 2
# @ohos.file.fs (File Management)

A
Annie_wang 已提交
3
The **fs** module provides APIs for file operations, including basic file management, directory management, file information statistics, and data read and write using a stream.
A
Annie_wang 已提交
4

A
Annie_wang 已提交
5 6
> **NOTE**
>
A
Annie_wang 已提交
7
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
A
Annie_wang 已提交
8 9 10 11 12 13 14 15 16

## Modules to Import

```js
import fs from '@ohos.file.fs';
```

## Guidelines

A
Annie_wang 已提交
17
Before using the APIs provided by this module to perform operations on a file or directory, obtain the application sandbox path of the file or directory as follows:
A
Annie_wang 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31

**Stage Model**

 ```js
import UIAbility from '@ohos.app.ability.UIAbility';

export default class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage) {
        let context = this.context;
        let pathDir = context.filesDir;
    }
}
 ```

A
Annie_wang 已提交
32
FA Model
A
Annie_wang 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

 ```js
 import featureAbility from '@ohos.ability.featureAbility';
 
 let context = featureAbility.getContext();
 context.getFilesDir().then((data) => {
      let pathDir = data;
 })
 ```

For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context).

## fs.stat

stat(file: string|number): Promise<Stat>

Obtains detailed file information. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                      |
| ------ | ------ | ---- | -------------------------- |
A
Annie_wang 已提交
57
| file   | string\|number | Yes  | Application sandbox path or file descriptor (FD) of the file.|
A
Annie_wang 已提交
58 59 60

**Return value**

A
Annie_wang 已提交
61 62 63
  | Type                          | Description        |
  | ---------------------------- | ---------- |
  | Promise<[Stat](#stat)> | Promise used to return the file information obtained.|
A
Annie_wang 已提交
64 65 66

**Error codes**

A
Annie_wang 已提交
67
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
68 69 70 71

**Example**

  ```js
A
Annie_wang 已提交
72
  let filePath = pathDir + "/test.txt";
A
Annie_wang 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
  fs.stat(filePath).then((stat) => {
      console.info("get file info succeed, the size of file is " + stat.size);
  }).catch((err) => {
      console.info("get file info failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.stat

stat(file: string|number, callback: AsyncCallback<Stat>): void

Obtains detailed file information. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type                              | Mandatory| Description                          |
| -------- | ---------------------------------- | ---- | ------------------------------ |
A
Annie_wang 已提交
92
| file     | string\|number                            | Yes  | Application sandbox path or FD of the file.    |
A
Annie_wang 已提交
93 94
| callback | AsyncCallback<[Stat](#stat)> | Yes  | Callback invoked to return the file information obtained.|

A
Annie_wang 已提交
95 96
**Error codes**

A
Annie_wang 已提交
97
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
98

A
Annie_wang 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
**Example**

  ```js
  fs.stat(pathDir, (err, stat) => {
    if (err) {
      console.info("get file info failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("get file info succeed, the size of file is " + stat.size);
    }
  });
  ```

## fs.statSync

statSync(file: string|number): Stat

Obtains detailed file information synchronously. 

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                      |
| ------ | ------ | ---- | -------------------------- |
A
Annie_wang 已提交
123
| file   | string\|number | Yes  | Application sandbox path or file descriptor (FD) of the file.|
A
Annie_wang 已提交
124 125 126

**Return value**

A
Annie_wang 已提交
127 128 129
  | Type           | Description        |
  | ------------- | ---------- |
  | [Stat](#stat) | File information obtained.|
A
Annie_wang 已提交
130 131 132

**Error codes**

A
Annie_wang 已提交
133
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

**Example**

  ```js
  let stat = fs.statSync(pathDir);
  console.info("get file info succeed, the size of file is " + stat.size);
  ```

## fs.access

access(path: string): Promise<boolean>

Checks whether a file exists. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                                                        |
| ------ | ------ | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
154
| path   | string | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
155 156 157

**Return value**

A
Annie_wang 已提交
158 159 160
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise<boolean> | Promise used to return the result. The value **true** means the file exists; the value **false** means the opposite.|
A
Annie_wang 已提交
161 162 163

**Error codes**

A
Annie_wang 已提交
164
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  fs.access(filePath).then((res) => {
    if (res) {
      console.info("file exists");
    }
  }).catch((err) => {
    console.info("access failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.access

access(path: string, callback: AsyncCallback<boolean>): void

Checks whether a file exists. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type                     | Mandatory| Description                                                        |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
191
| path     | string                    | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
192 193 194 195
| callback | AsyncCallback<boolean> | Yes  | Callback invoked to return the result. The value **true** means the file exists; the value **false** means the opposite.|

**Error codes**

A
Annie_wang 已提交
196
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  fs.access(filePath, (err, res) => {
    if (err) {
      console.info("access failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      if (res) {
        console.info("file exists");
      }
    }
  });
  ```

## fs.accessSync

accessSync(path: string): boolean

Synchronously checks whether a file exists.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                                                        |
| ------ | ------ | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
225 226 227 228
| path   | string | Yes  | Application sandbox path of the file.                                  |

**Return value**

A
Annie_wang 已提交
229 230 231
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | boolean | Returns **true** if the file exists; returns **false** otherwise.|
A
Annie_wang 已提交
232 233 234

**Error codes**

A
Annie_wang 已提交
235
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  try {
      let res = fs.accessSync(filePath);
      if (res) {
        console.info("file exists");
      }
  } catch(err) {
      console.info("accessSync failed with error message: " + err.message + ", error code: " + err.code);
  }
  ```


## fs.close

A
Annie_wang 已提交
254
close(file: number|File): Promise<void>
A
Annie_wang 已提交
255 256 257 258 259 260 261

Closes a file. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
262 263
  | Name | Type    | Mandatory  | Description          |
  | ---- | ------ | ---- | ------------ |
A
Annie_wang 已提交
264
  | file   | number\|[File](#file) | Yes   | File object or FD of the file to close.|
A
Annie_wang 已提交
265 266 267

**Return value**

A
Annie_wang 已提交
268 269 270
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise<void> | Promise that returns no value.|
A
Annie_wang 已提交
271 272 273

**Error codes**

A
Annie_wang 已提交
274
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath);
  fs.close(file).then(() => {
      console.info("File closed");
  }).catch((err) => {
      console.info("close file failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.close

A
Annie_wang 已提交
290
close(file: number|File, callback: AsyncCallback<void>): void
A
Annie_wang 已提交
291 292 293 294 295 296 297

Closes a file. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
298 299
  | Name     | Type                       | Mandatory  | Description          |
  | -------- | ------------------------- | ---- | ------------ |
A
Annie_wang 已提交
300
  | file       | number\|[File](#file)                  | Yes   | File object or FD of the file to close.|
A
Annie_wang 已提交
301
  | callback | AsyncCallback<void> | Yes   | Callback invoked immediately after the file is closed.|
A
Annie_wang 已提交
302 303 304

**Error codes**

A
Annie_wang 已提交
305
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
306 307 308 309 310 311 312 313 314 315 316

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath);
  fs.close(file, (err) => {
    if (err) {
      console.info("close file failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("close file success");
A
Annie_wang 已提交
317
      fs.closeSync(file);
A
Annie_wang 已提交
318 319 320 321 322 323
    }
  });
  ```

## fs.closeSync

A
Annie_wang 已提交
324
closeSync(file: number|File): void
A
Annie_wang 已提交
325 326 327 328 329 330 331

Synchronously closes a file.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
332 333
  | Name | Type    | Mandatory  | Description          |
  | ---- | ------ | ---- | ------------ |
A
Annie_wang 已提交
334
  | file   | number\|[File](#file) | Yes   | File object or FD of the file to close.|
A
Annie_wang 已提交
335 336 337

**Error codes**

A
Annie_wang 已提交
338
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath);
  fs.closeSync(file);
  ```

## fs.copyFile

copyFile(src: string|number, dest: string|number, mode?: number): Promise<void>

Copies a file. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
358 359 360 361 362
  | Name | Type                        | Mandatory  | Description                                      |
  | ---- | -------------------------- | ---- | ---------------------------------------- |
  | src  | string\|number | Yes   | Path or FD of the file to copy.                     |
  | dest | string\|number | Yes   | Destination path of the file or FD of the file created.                         |
  | mode | number                     | No   | Whether to overwrite the file with the same name in the destination directory. The default value is **0**, which is the only value supported.<br>**0**: overwrite the file with the same name.|
A
Annie_wang 已提交
363 364 365

**Return value**

A
Annie_wang 已提交
366 367 368
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
369 370 371

**Error codes**

A
Annie_wang 已提交
372
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
373 374 375 376

**Example**

  ```js
A
Annie_wang 已提交
377 378
  let srcPath = pathDir + "/srcDir/test.txt";
  let dstPath = pathDir + "/dstDir/test.txt";
A
Annie_wang 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
  fs.copyFile(srcPath, dstPath).then(() => {
      console.info("copy file succeed");
  }).catch((err) => {
      console.info("copy file failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.copyFile

copyFile(src: string|number, dest: string|number, mode?: number, callback: AsyncCallback&lt;void&gt;): void

Copies a file. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
396 397 398 399 400 401
  | Name     | Type                        | Mandatory  | Description                                      |
  | -------- | -------------------------- | ---- | ---------------------------------------- |
  | src      | string\|number | Yes   | Path or FD of the file to copy.                     |
  | dest     | string\|number | Yes   | Destination path of the file or FD of the file created.                         |
  | mode     | number                     | No   | Whether to overwrite the file with the same name in the destination directory. The default value is **0**, which is the only value supported.<br>**0**: overwrite the file with the same name and truncate the part that is not overwritten.|
  | callback | AsyncCallback&lt;void&gt;  | Yes   | Callback invoked immediately after the file is copied.                            |
A
Annie_wang 已提交
402 403 404

**Error codes**

A
Annie_wang 已提交
405
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
406 407 408 409

**Example**

  ```js
A
Annie_wang 已提交
410 411
  let srcPath = pathDir + "/srcDir/test.txt";
  let dstPath = pathDir + "/dstDir/test.txt";
A
Annie_wang 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
  fs.copyFile(srcPath, dstPath, (err) => {
    if (err) {
      console.info("copy file failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("copy file success");
    }
  });
  ```


## fs.copyFileSync

copyFileSync(src: string|number, dest: string|number, mode?: number): void

Synchronously copies a file.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
432 433 434 435 436
  | Name | Type                        | Mandatory  | Description                                      |
  | ---- | -------------------------- | ---- | ---------------------------------------- |
  | src  | string\|number | Yes   | Path or FD of the file to copy.                     |
  | dest | string\|number | Yes   | Destination path of the file or FD of the file created.                         |
  | mode | number                     | No   | Whether to overwrite the file with the same name in the destination directory. The default value is **0**, which is the only value supported.<br>**0**: overwrite the file with the same name and truncate the part that is not overwritten.|
A
Annie_wang 已提交
437 438 439

**Error codes**

A
Annie_wang 已提交
440
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
441 442 443 444

**Example**

  ```js
A
Annie_wang 已提交
445 446
  let srcPath = pathDir + "/srcDir/test.txt";
  let dstPath = pathDir + "/dstDir/test.txt";
A
Annie_wang 已提交
447 448 449
  fs.copyFileSync(srcPath, dstPath);
  ```

A
Annie_wang 已提交
450 451 452 453 454 455 456 457 458 459 460 461 462 463
## fs.copyDir<sup>10+</sup>

copyDir(src: string, dest: string, mode?: number): Promise\<void>

Copies a directory to the specified directory. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | src | string | Yes   | Application sandbox path of the directory to copy.|
  | dest | string | Yes   | Application sandbox path of the destination directory.|
A
Annie_wang 已提交
464
  | mode | number | No   | Copy mode. The default value is **0**.<br>- **0**: Throw an exception if a file conflict occurs.<br>Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles10)> format.<br>- **1**: Forcibly overwrite the files with the same name in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.|
A
Annie_wang 已提交
465 466 467 468 469 470 471 472 473

**Return value**

  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

A
Annie_wang 已提交
474
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497

**Example**

  ```js
  // Copy srcPath to destPath.
  let srcPath = pathDir + "/srcDir/";
  let destPath = pathDir + "/destDir/";
  fs.copyDir(srcPath, destPath, 0).then(() => {
    console.info("copy directory succeed");
  }).catch((err) => {
    if (err.code == 13900015) {
      for (let i = 0; i < err.data.length; i++) {
        console.info("copy directory failed with conflicting files: " + err.data[i].srcFile +
          " " + err.data[i].destFile);
      }
    } else {
      console.info("copy directory failed with error message: " + err.message + ", error code: " + err.code);
    }
  });
  ```

## fs.copyDir<sup>10+</sup>

A
Annie_wang 已提交
498
copyDir(src: string, dest: string, mode?: number, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void
A
Annie_wang 已提交
499 500 501 502 503 504 505 506 507 508 509

Copies a directory to the specified directory. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | src | string | Yes   | Application sandbox path of the directory to copy.|
  | dest | string | Yes   | Application sandbox path of the destination directory.|
A
Annie_wang 已提交
510 511
  | mode | number | No   | Copy mode. The default value is **0**.<br>- **0**: Throw an exception if a file conflict occurs.<br>Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles10)> format.<br>- **1**: Forcibly overwrite the files with the same name in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.|
  | callback | AsyncCallback&lt;void, Array&lt;[ConflictFiles](#conflictfiles10)&gt;&gt; | Yes   | Callback invoked immediately after the directory is copied.             |
A
Annie_wang 已提交
512 513 514

**Error codes**

A
Annie_wang 已提交
515
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

**Example**

  ```js
  // Copy srcPath to destPath.
  let srcPath = pathDir + "/srcDir/";
  let destPath = pathDir + "/destDir/";
  fs.copyDir(srcPath, destPath, 0, (err) => {
    if (err && err.code == 13900015) {
      for (let i = 0; i < err.data.length; i++) {
        console.info("copy directory failed with conflicting files: " + err.data[i].srcFile +
          " " + err.data[i].destFile);
      }
    } else if (err) {
      console.info("copy directory failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("copy directory succeed");
    }  
  });
  ```

A
Annie_wang 已提交
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
## fs.dup<sup>10+</sup>

dup(fd: number): File

Opens a **File** object based on the specified FD.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | fd | number | Yes   | FD of the file.|

**Return value**

  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | [File](#file) | File object opened.|

**Error codes**

For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).

**Example**

  ```js
  // convert fd to file
  let fd = 0;  // fd comes from other modules
  let file = fs.dup(fd);
  console.info("The name of the file is " + file.name);
  fs.closeSync(file);
  ```


A
Annie_wang 已提交
572 573 574 575 576 577 578 579 580 581 582 583
## fs.mkdir

mkdir(path: string): Promise&lt;void&gt;

Creates a directory. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                                                        |
| ------ | ------ | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
584
| path   | string | Yes  | Application sandbox path of the directory.                                  |
A
Annie_wang 已提交
585 586 587

**Return value**

A
Annie_wang 已提交
588 589 590
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
591 592 593

**Error codes**

A
Annie_wang 已提交
594
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
595 596 597 598

**Example**

  ```js
A
Annie_wang 已提交
599
  let dirPath = pathDir + "/testDir";
A
Annie_wang 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
  fs.mkdir(dirPath).then(() => {
      console.info("Directory created");
  }).catch((err) => {
      console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.mkdir

mkdir(path: string, callback: AsyncCallback&lt;void&gt;): void

Creates a directory. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type                     | Mandatory| Description                                                        |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
619
| path     | string                    | Yes  | Application sandbox path of the directory.                                  |
A
Annie_wang 已提交
620 621
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked when the directory is created asynchronously.                            |

A
Annie_wang 已提交
622 623
**Error codes**

A
Annie_wang 已提交
624
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
625

A
Annie_wang 已提交
626 627 628
**Example**

  ```js
A
Annie_wang 已提交
629
  let dirPath = pathDir + "/testDir";
A
Annie_wang 已提交
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
  fs.mkdir(dirPath, (err) => {
    if (err) {
      console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("mkdir success");
    }
  });
  ```

## fs.mkdirSync

mkdirSync(path: string): void

Synchronously creates a directory.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                                                        |
| ------ | ------ | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
651
| path   | string | Yes  | Application sandbox path of the directory.                                  |
A
Annie_wang 已提交
652

A
Annie_wang 已提交
653 654
**Error codes**

A
Annie_wang 已提交
655
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
656

A
Annie_wang 已提交
657 658 659
**Example**

  ```js
A
Annie_wang 已提交
660
  let dirPath = pathDir + "/testDir";
A
Annie_wang 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
  fs.mkdirSync(dirPath);
  ```

## fs.open

open(path: string, mode?: number): Promise&lt;File&gt;

Opens a file. This API uses a promise to return the result. File uniform resource identifiers (URIs) are supported. 

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                                                        |
| ------ | ------ | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
676
| path   | string | Yes  | Application sandbox path or URI of the file.                                  |
A
Annie_wang 已提交
677
| mode  | number | No  | [Mode](#openmode) for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.<br>- **OpenMode.READ_ONLY(0o0)**: Open the file in read-only mode.<br>- **OpenMode.WRITE_ONLY(0o1)**: Open the file in write-only mode.<br>- **OpenMode.READ_WRITE(0o2)**: Open the file in read/write mode.<br>You can also specify the following options, separated by a bitwise OR operator (&#124;). By default, no additional options are given.<br>- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.<br>- **OpenMode.TRUNC(0o1000)**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.<br>- **OpenMode.APPEND(0o2000)**: Open the file in append mode. New data will be added to the end of the file.<br>- **OpenMode.NONBLOCK(0o4000)**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the opened file and in subsequent I/Os.<br>- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.<br>- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.<br>- **OpenMode.SYNC(0o4010000)**: Open the file in synchronous I/O mode.|
A
Annie_wang 已提交
678 679 680

**Return value**

A
Annie_wang 已提交
681 682
  | Type                   | Description         |
  | --------------------- | ----------- |
A
Annie_wang 已提交
683
  | Promise&lt;[File](#file)&gt; | Promise used to return the **File** object.|
A
Annie_wang 已提交
684 685 686

**Error codes**

A
Annie_wang 已提交
687
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE).then((file) => {
      console.info("file fd: " + file.fd);
  }).catch((err) => {
      console.info("open file failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```


## fs.open

open(path: string, mode?: number, callback: AsyncCallback&lt;File&gt;): void

Opens a file. This API uses an asynchronous callback to return the result. File URIs are supported. 

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type                           | Mandatory| Description                                                        |
| -------- | ------------------------------- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
713
| path     | string                          | Yes  | Application sandbox path or URI of the file.                                  |
A
Annie_wang 已提交
714
| mode  | number | No  | [Mode](#openmode) for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.<br>- **OpenMode.READ_ONLY(0o0)**: Open the file in read-only mode.<br>- **OpenMode.WRITE_ONLY(0o1)**: Open the file in write-only mode.<br>- **OpenMode.READ_WRITE(0o2)**: Open the file in read/write mode.<br>You can also specify the following options, separated by a bitwise OR operator (&#124;). By default, no additional options are given.<br>- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.<br>- **OpenMode.TRUNC(0o1000)**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.<br>- **OpenMode.APPEND(0o2000)**: Open the file in append mode. New data will be added to the end of the file.<br>- **OpenMode.NONBLOCK(0o4000)**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the opened file and in subsequent I/Os.<br>- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.<br>- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.<br>- **OpenMode.SYNC(0o4010000)**: Open the file in synchronous I/O mode.|
A
Annie_wang 已提交
715

A
Annie_wang 已提交
716 717
**Error codes**

A
Annie_wang 已提交
718
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
719

A
Annie_wang 已提交
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE, (err, file) => {
    if (err) {
      console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("file fd: " + file.fd);
    }
  });
  ```

## fs.openSync

openSync(path: string, mode?: number): File

Synchronously opens a file. File URIs are supported. 

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                                                        |
| ------ | ------ | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
745
| path   | string | Yes  | Application sandbox path or URI of the file.                                  |
A
Annie_wang 已提交
746
| mode  | number | No  | [Mode](#openmode) for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.<br>- **OpenMode.READ_ONLY(0o0)**: Open the file in read-only mode.<br>- **OpenMode.WRITE_ONLY(0o1)**: Open the file in write-only mode.<br>- **OpenMode.READ_WRITE(0o2)**: Open the file in read/write mode.<br>You can also specify the following options, separated by a bitwise OR operator (&#124;). By default, no additional options are given.<br>- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.<br>- **OpenMode.TRUNC(0o1000)**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.<br>- **OpenMode.APPEND(0o2000)**: Open the file in append mode. New data will be added to the end of the file.<br>- **OpenMode.NONBLOCK(0o4000)**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the opened file and in subsequent I/Os.<br>- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.<br>- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.<br>- **OpenMode.SYNC(0o4010000)**: Open the file in synchronous I/O mode.|
A
Annie_wang 已提交
747 748 749

**Return value**

A
Annie_wang 已提交
750 751 752
  | Type    | Description         |
  | ------ | ----------- |
  | [File](#file) | File object opened.|
A
Annie_wang 已提交
753 754 755

**Error codes**

A
Annie_wang 已提交
756
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  console.info("file fd: " + file.fd);
  fs.closeSync(file);
  ```

## fs.read

read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): Promise&lt;number&gt;

Reads data from a file. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name | Type       | Mandatory| Description                                                        |
| ------- | ----------- | ---- | ------------------------------------------------------------ |
| fd      | number      | Yes  | FD of the file.                                    |
| buffer  | ArrayBuffer | Yes  | Buffer used to store the file data read.                          |
A
Annie_wang 已提交
781
| options | Object      | No  | The options are as follows:<br>- **offset** (number): start position to read the data. This parameter is optional. By default, data is read from the current position.<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.|
A
Annie_wang 已提交
782 783 784

**Return value**

A
Annie_wang 已提交
785 786 787
  | Type                                | Description    |
  | ---------------------------------- | ------ |
  | Promise&lt;number&gt; | Promise used to return the data read.|
A
Annie_wang 已提交
788 789 790

**Error codes**

A
Annie_wang 已提交
791
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
792 793 794 795 796 797 798 799 800

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
  let buf = new ArrayBuffer(4096);
  fs.read(file.fd, buf).then((readLen) => {
      console.info("Read file data successfully");
A
Annie_wang 已提交
801
      console.info(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen))));
A
Annie_wang 已提交
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
      fs.closeSync(file);
  }).catch((err) => {
      console.info("read file data failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.read

read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }, callback: AsyncCallback&lt;number&gt;): void

Reads data from a file. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
818 819 820 821
  | Name     | Type                                      | Mandatory  | Description                                      |
  | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
  | fd       | number                                   | Yes   | FD of the file.                            |
  | buffer   | ArrayBuffer                              | Yes   | Buffer used to store the file data read.                       |
A
Annie_wang 已提交
822
  | options | Object      | No  | The options are as follows:<br>- **offset** (number): start position to read the data. This parameter is optional. By default, data is read from the current position.<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.|
A
Annie_wang 已提交
823
  | callback | AsyncCallback&lt;number&gt; | Yes   | Callback invoked when the data is read asynchronously.                            |
A
Annie_wang 已提交
824 825 826

**Error codes**

A
Annie_wang 已提交
827
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
828 829 830 831 832 833 834 835 836 837 838 839

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
  let buf = new ArrayBuffer(4096);
  fs.read(file.fd, buf, (err, readLen) => {
    if (err) {
      console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("Read file data successfully");
A
Annie_wang 已提交
840
      console.info(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen))));
A
Annie_wang 已提交
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
      fs.closeSync(file);
    }
  });
  ```

## fs.readSync

readSync(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number

Synchronously reads data from a file.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
856 857 858 859
  | Name    | Type         | Mandatory  | Description                                      |
  | ------- | ----------- | ---- | ---------------------------------------- |
  | fd      | number      | Yes   | FD of the file.                            |
  | buffer  | ArrayBuffer | Yes   | Buffer used to store the file data read.                       |
A
Annie_wang 已提交
860
  | options | Object      | No  | The options are as follows:<br>- **offset** (number): start position to read the data. This parameter is optional. By default, data is read from the current position.<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.|
A
Annie_wang 已提交
861 862 863

**Return value**

A
Annie_wang 已提交
864 865 866
  | Type    | Description      |
  | ------ | -------- |
  | number | Length of the data read.|
A
Annie_wang 已提交
867 868 869

**Error codes**

A
Annie_wang 已提交
870
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
  let buf = new ArrayBuffer(4096);
  let num = fs.readSync(file.fd, buf);
  fs.closeSync(file);
  ```

## fs.rmdir

rmdir(path: string): Promise&lt;void&gt;

Deletes a directory. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                      |
| ------ | ------ | ---- | -------------------------- |
A
Annie_wang 已提交
894
| path   | string | Yes  | Application sandbox path of the directory.|
A
Annie_wang 已提交
895 896 897

**Return value**

A
Annie_wang 已提交
898 899 900
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
901 902 903

**Error codes**

A
Annie_wang 已提交
904
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
905 906 907 908

**Example**

  ```js
A
Annie_wang 已提交
909
  let dirPath = pathDir + "/testDir";
A
Annie_wang 已提交
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
  fs.rmdir(dirPath).then(() => {
      console.info("Directory deleted");
  }).catch((err) => {
      console.info("rmdir failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.rmdir

rmdir(path: string, callback: AsyncCallback&lt;void&gt;): void

Deletes a directory. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type                     | Mandatory| Description                      |
| -------- | ------------------------- | ---- | -------------------------- |
A
Annie_wang 已提交
929
| path     | string                    | Yes  | Application sandbox path of the directory.|
A
Annie_wang 已提交
930 931
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked when the directory is deleted asynchronously.  |

A
Annie_wang 已提交
932 933
**Error codes**

A
Annie_wang 已提交
934
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
935

A
Annie_wang 已提交
936 937 938
**Example**

  ```js
A
Annie_wang 已提交
939
  let dirPath = pathDir + "/testDir";
A
Annie_wang 已提交
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
  fs.rmdir(dirPath, (err) => {
    if (err) {
      console.info("rmdir failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("Directory deleted");
    }
  });
  ```

## fs.rmdirSync

rmdirSync(path: string): void

Synchronously deletes a directory.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                      |
| ------ | ------ | ---- | -------------------------- |
A
Annie_wang 已提交
961
| path   | string | Yes  | Application sandbox path of the directory.|
A
Annie_wang 已提交
962

A
Annie_wang 已提交
963 964
**Error codes**

A
Annie_wang 已提交
965
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
966

A
Annie_wang 已提交
967 968 969
**Example**

  ```js
A
Annie_wang 已提交
970
  let dirPath = pathDir + "/testDir";
A
Annie_wang 已提交
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
  fs.rmdirSync(dirPath);
  ```

## fs.unlink

unlink(path: string): Promise&lt;void&gt;

Deletes a file. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                      |
| ------ | ------ | ---- | -------------------------- |
A
Annie_wang 已提交
986
| path   | string | Yes  | Application sandbox path of the file.|
A
Annie_wang 已提交
987 988 989

**Return value**

A
Annie_wang 已提交
990 991 992
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
993 994 995

**Error codes**

A
Annie_wang 已提交
996
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  fs.unlink(filePath).then(() => {
      console.info("File deleted");
  }).catch((err) => {
      console.info("remove file failed with error message: " + err.message + ", error code: " + err.codeor);
  });
  ```

## fs.unlink

unlink(path: string, callback: AsyncCallback&lt;void&gt;): void

Deletes a file. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type                     | Mandatory| Description                      |
| -------- | ------------------------- | ---- | -------------------------- |
A
Annie_wang 已提交
1021
| path     | string                    | Yes  | Application sandbox path of the file.|
A
Annie_wang 已提交
1022
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked immediately after the file is deleted.  |
A
Annie_wang 已提交
1023

A
Annie_wang 已提交
1024 1025
**Error codes**

A
Annie_wang 已提交
1026
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1027

A
Annie_wang 已提交
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  fs.unlink(filePath, (err) => {
    if (err) {
      console.info("remove file failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("File deleted");
    }
  });
  ```

## fs.unlinkSync

unlinkSync(path: string): void

Synchronously deletes a file.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                      |
| ------ | ------ | ---- | -------------------------- |
A
Annie_wang 已提交
1053
| path   | string | Yes  | Application sandbox path of the file.|
A
Annie_wang 已提交
1054

A
Annie_wang 已提交
1055 1056
**Error codes**

A
Annie_wang 已提交
1057
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1058

A
Annie_wang 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  fs.unlinkSync(filePath);
  ```


## fs.write

write(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): Promise&lt;number&gt;

Writes data into a file. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
1077 1078 1079 1080
  | Name    | Type                             | Mandatory  | Description                                      |
  | ------- | ------------------------------- | ---- | ---------------------------------------- |
  | fd      | number                          | Yes   | FD of the file.                            |
  | buffer  | ArrayBuffer\|string | Yes   | Data to write. It can be a string or data from a buffer.                    |
A
Annie_wang 已提交
1081
  | options | Object                          | No   | The options are as follows:<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported currently.|
A
Annie_wang 已提交
1082 1083 1084

**Return value**

A
Annie_wang 已提交
1085 1086 1087
  | Type                   | Description      |
  | --------------------- | -------- |
  | Promise&lt;number&gt; | Promise used to return the length of the data written.|
A
Annie_wang 已提交
1088 1089 1090

**Error codes**

A
Annie_wang 已提交
1091
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  fs.write(file.fd, "hello, world").then((writeLen) => {
    console.info("write data to file succeed and size is:" + writeLen);
    fs.closeSync(file);
  }).catch((err) => {
    console.info("write data to file failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.write

write(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback&lt;number&gt;): void

Writes data into a file. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
1116 1117 1118 1119
  | Name     | Type                             | Mandatory  | Description                                      |
  | -------- | ------------------------------- | ---- | ---------------------------------------- |
  | fd       | number                          | Yes   | FD of the file.                            |
  | buffer   | ArrayBuffer\|string | Yes   | Data to write. It can be a string or data from a buffer.                    |
A
Annie_wang 已提交
1120
  | options | Object                          | No   | The options are as follows:<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported currently.|
A
Annie_wang 已提交
1121
  | callback | AsyncCallback&lt;number&gt;     | Yes   | Callback invoked when the data is written asynchronously.                      |
A
Annie_wang 已提交
1122 1123 1124

**Error codes**

A
Annie_wang 已提交
1125
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  fs.write(file.fd, "hello, world", (err, writeLen) => {
    if (err) {
      console.info("write failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("write data to file succeed and size is:" + writeLen);
      fs.closeSync(file);
    }
  });
  ```

## fs.writeSync

writeSync(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): number

Synchronously writes data into a file.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
1152 1153 1154 1155
  | Name    | Type                             | Mandatory  | Description                                      |
  | ------- | ------------------------------- | ---- | ---------------------------------------- |
  | fd      | number                          | Yes   | FD of the file.                            |
  | buffer  | ArrayBuffer\|string | Yes   | Data to write. It can be a string or data from a buffer.                    |
A
Annie_wang 已提交
1156
  | options | Object                          | No   | The options are as follows:<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported currently.|
A
Annie_wang 已提交
1157 1158 1159

**Return value**

A
Annie_wang 已提交
1160 1161 1162
  | Type    | Description      |
  | ------ | -------- |
  | number | Length of the data written in the file.|
A
Annie_wang 已提交
1163 1164 1165

**Error codes**

A
Annie_wang 已提交
1166
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  let writeLen = fs.writeSync(file.fd, "hello, world");
  console.info("write data to file succeed and size is:" + writeLen);
  fs.closeSync(file);
  ```

## fs.truncate

truncate(file: string|number, len?: number): Promise&lt;void&gt;

Truncates a file. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                            |
| ------ | ------ | ---- | -------------------------------- |
A
Annie_wang 已提交
1190 1191
| file   | string\|number | Yes  | Application sandbox path or FD of the file.      |
| len    | number | No  | File length, in bytes, after truncation. The default value is **0**.|
A
Annie_wang 已提交
1192 1193 1194

**Return value**

A
Annie_wang 已提交
1195 1196 1197
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
1198 1199 1200

**Error codes**

A
Annie_wang 已提交
1201
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let len = 5;
  fs.truncate(filePath, len).then(() => {
      console.info("File truncated");
  }).catch((err) => {
      console.info("truncate file failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.truncate

truncate(file: string|number, len?: number, callback: AsyncCallback&lt;void&gt;): void

Truncates a file. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type                     | Mandatory| Description                            |
| -------- | ------------------------- | ---- | -------------------------------- |
A
Annie_wang 已提交
1227 1228
| file     | string\|number                    | Yes  | Application sandbox path or FD of the file.      |
| len      | number                    | No  | File length, in bytes, after truncation. The default value is **0**.|
A
Annie_wang 已提交
1229 1230
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback that returns no value.  |

A
Annie_wang 已提交
1231 1232
**Error codes**

A
Annie_wang 已提交
1233
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1234

A
Annie_wang 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let len = 5;
  fs.truncate(filePath, len, (err) => {
    if (err) {
      console.info("truncate failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("truncate success");
    }
  });
  ```

## fs.truncateSync

truncateSync(file: string|number, len?: number): void

Synchronously truncates a file.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                            |
| ------ | ------ | ---- | -------------------------------- |
A
Annie_wang 已提交
1261 1262
| file   | string\|number | Yes  | Application sandbox path or FD of the file.      |
| len    | number | No  | File length, in bytes, after truncation. The default value is **0**.|
A
Annie_wang 已提交
1263

A
Annie_wang 已提交
1264 1265
**Error codes**

A
Annie_wang 已提交
1266
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1267

A
Annie_wang 已提交
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let len = 5;
  fs.truncateSync(filePath, len);
  ```

## fs.readText

readText(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }): Promise&lt;string&gt;

Reads the text content of a file. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type  | Mandatory| Description                                                        |
| -------- | ------ | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
1288
| filePath | string | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
1289
| options  | Object | No  | The options are as follows:<br>- **offset** (number): start position to read the data. This parameter is optional. By default, data is read from the current position.<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the file length.<br>- **encoding** (string): format of the data (string) to be encoded. The default value is **'utf-8'**, which is the only value supported.|
A
Annie_wang 已提交
1290 1291 1292

**Return value**

A
Annie_wang 已提交
1293 1294
  | Type                   | Description        |
  | --------------------- | ---------- |
A
Annie_wang 已提交
1295
  | Promise&lt;string&gt; | Promise used to return the file content read.|
A
Annie_wang 已提交
1296 1297 1298

**Error codes**

A
Annie_wang 已提交
1299
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  fs.readText(filePath).then((str) => {
      console.info("readText succeed:" + str);
  }).catch((err) => {
      console.info("readText failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.readText

readText(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback&lt;string&gt;): void

Reads the text content of a file. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type                       | Mandatory| Description                                                        |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
1324
| filePath | string                      | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
1325
| options  | Object                      | No  | The options are as follows:<br>- **offset** (number): start position to read the data. This parameter is optional. By default, data is read from the current position.<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the file length.<br>- **encoding**: format of the data to be encoded. The default value is **'utf-8'**, which is the only value supported.|
A
Annie_wang 已提交
1326
| callback | AsyncCallback&lt;string&gt; | Yes  | Callback invoked to return the content read.                        |
A
Annie_wang 已提交
1327

A
Annie_wang 已提交
1328 1329
**Error codes**

A
Annie_wang 已提交
1330
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1331

A
Annie_wang 已提交
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  fs.readText(filePath, { offset: 1, encoding: 'UTF-8' }, (err, str) => {
    if (err) {
      console.info("read text failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("readText succeed:" + str);
    }
  });
  ```

## fs.readTextSync

readTextSync(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }): string

Synchronously reads the text of a file. 

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type  | Mandatory| Description                                                        |
| -------- | ------ | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
1357
| filePath | string | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
1358
| options  | Object | No  | The options are as follows:<br>- **offset** (number): start position to read the data. This parameter is optional. By default, data is read from the current position.<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the file length.<br>- **encoding** (string): format of the data (string) to be encoded. The default value is **'utf-8'**, which is the only value supported.|
A
Annie_wang 已提交
1359 1360 1361

**Return value**

A
Annie_wang 已提交
1362 1363
  | Type  | Description                |
  | ------ | -------------------- |
A
Annie_wang 已提交
1364
  | string | Returns the content of the file read.|
A
Annie_wang 已提交
1365 1366 1367

**Error codes**

A
Annie_wang 已提交
1368
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let str = fs.readTextSync(filePath, {offset: 1, length: 3});
  console.info("readText succeed:" + str);
  ```

## fs.lstat

lstat(path: string): Promise&lt;Stat&gt;

Obtains information about a symbolic link. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                                  |
| ------ | ------ | ---- | -------------------------------------- |
A
Annie_wang 已提交
1390
| path   | string | Yes  | Application sandbox path of the file.|
A
Annie_wang 已提交
1391 1392 1393

**Return value**

A
Annie_wang 已提交
1394 1395 1396
  | Type                          | Description        |
  | ---------------------------- | ---------- |
  | Promise&lt;[Stat](#stat)&gt; | Promise used to return the symbolic link information obtained. For details, see **stat**.|
A
Annie_wang 已提交
1397 1398 1399

**Error codes**

A
Annie_wang 已提交
1400
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  fs.lstat(filePath).then((stat) => {
      console.info("get link status succeed, the size of file is" + stat.size);
  }).catch((err) => {
      console.info("get link status failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.lstat

lstat(path: string, callback: AsyncCallback&lt;Stat&gt;): void

Obtains information about a symbolic link. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type                              | Mandatory| Description                                  |
| -------- | ---------------------------------- | ---- | -------------------------------------- |
A
Annie_wang 已提交
1425
| path     | string                             | Yes  | Application sandbox path of the file.|
A
Annie_wang 已提交
1426
| callback | AsyncCallback&lt;[Stat](#stat)&gt; | Yes  | Callback invoked to return the symbolic link information obtained.      |
A
Annie_wang 已提交
1427

A
Annie_wang 已提交
1428 1429
**Error codes**

A
Annie_wang 已提交
1430
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1431

A
Annie_wang 已提交
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  fs.lstat(filePath, (err, stat) => {
      if (err) {
        console.info("lstat failed with error message: " + err.message + ", error code: " + err.code);
      } else {
        console.info("get link status succeed, the size of file is" + stat.size);
      }
  });
  ```

## fs.lstatSync

lstatSync(path: string): Stat

Obtains information about a symbolic link synchronously.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                                  |
| ------ | ------ | ---- | -------------------------------------- |
A
Annie_wang 已提交
1457
| path   | string | Yes  | Application sandbox path of the file.|
A
Annie_wang 已提交
1458 1459 1460

**Return value**

A
Annie_wang 已提交
1461 1462 1463
  | Type           | Description        |
  | ------------- | ---------- |
  | [Stat](#stat) | File information obtained.|
A
Annie_wang 已提交
1464 1465 1466

**Error codes**

A
Annie_wang 已提交
1467
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let stat = fs.lstatSync(filePath);
  ```

## fs.rename

rename(oldPath: string, newPath: string): Promise&lt;void&gt;

A
Annie_wang 已提交
1480
Renames a file or folder. This API uses a promise to return the result.
A
Annie_wang 已提交
1481 1482 1483 1484 1485 1486 1487

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name | Type  | Mandatory| Description                        |
| ------- | ------ | ---- | ---------------------------- |
A
Annie_wang 已提交
1488 1489
| oldPath | string | Yes  | Application sandbox path of the file to rename.|
| newPath | string | Yes  | Application sandbox path of the renamed file.  |
A
Annie_wang 已提交
1490 1491 1492

**Return value**

A
Annie_wang 已提交
1493 1494 1495
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
1496 1497 1498

**Error codes**

A
Annie_wang 已提交
1499
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1500 1501 1502 1503 1504

**Example**

  ```js
  let srcFile = pathDir + "/test.txt";
A
Annie_wang 已提交
1505
  let dstFile = pathDir + "/new.txt";
A
Annie_wang 已提交
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
  fs.rename(srcFile, dstFile).then(() => {
      console.info("File renamed");
  }).catch((err) => {
      console.info("rename failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.rename

rename(oldPath: string, newPath: string, callback: AsyncCallback&lt;void&gt;): void

A
Annie_wang 已提交
1517
Renames a file or folder. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
1518 1519 1520 1521 1522 1523 1524

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type                     | Mandatory| Description                        |
| -------- | ------------------------- | ---- | ---------------------------- |
A
Annie_wang 已提交
1525 1526
| oldPath | string | Yes  | Application sandbox path of the file to rename.|
| newPath | string | Yes  | Application sandbox path of the renamed file.  |
A
Annie_wang 已提交
1527 1528
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked when the file is asynchronously renamed.  |

A
Annie_wang 已提交
1529 1530
**Error codes**

A
Annie_wang 已提交
1531
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1532

A
Annie_wang 已提交
1533 1534 1535 1536
**Example**

  ```js
  let srcFile = pathDir + "/test.txt";
A
Annie_wang 已提交
1537
  let dstFile = pathDir + "/new.txt";
A
Annie_wang 已提交
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
  fs.rename(srcFile, dstFile, (err) => {
    if (err) {
      console.info("rename failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("rename success");
    }
  });
  ```

## fs.renameSync

renameSync(oldPath: string, newPath: string): void

A
Annie_wang 已提交
1551
Renames a file or folder synchronously.
A
Annie_wang 已提交
1552 1553 1554 1555 1556 1557 1558

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name | Type  | Mandatory| Description                        |
| ------- | ------ | ---- | ---------------------------- |
A
Annie_wang 已提交
1559 1560
| oldPath | string | Yes  | Application sandbox path of the file to rename.|
| newPath | string | Yes  | Application sandbox path of the renamed file.  |
A
Annie_wang 已提交
1561

A
Annie_wang 已提交
1562 1563
**Error codes**

A
Annie_wang 已提交
1564
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1565

A
Annie_wang 已提交
1566 1567 1568 1569
**Example**

  ```js
  let srcFile = pathDir + "/test.txt";
A
Annie_wang 已提交
1570
  let dstFile = pathDir + "/new.txt";
A
Annie_wang 已提交
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
  fs.renameSync(srcFile, dstFile);
  ```

## fs.fsync

fsync(fd: number): Promise&lt;void&gt;

Flushes data of a file to disk. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
1584 1585 1586
  | Name | Type    | Mandatory  | Description          |
  | ---- | ------ | ---- | ------------ |
  | fd   | number | Yes   | FD of the file.|
A
Annie_wang 已提交
1587 1588 1589

**Return value**

A
Annie_wang 已提交
1590 1591 1592
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
1593 1594 1595

**Error codes**

A
Annie_wang 已提交
1596
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1597 1598 1599 1600 1601 1602 1603 1604

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath);
  fs.fsync(file.fd).then(() => {
      console.info("Data flushed");
A
Annie_wang 已提交
1605
      fs.closeSync(file);
A
Annie_wang 已提交
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
  }).catch((err) => {
      console.info("sync data failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.fsync

fsync(fd: number, callback: AsyncCallback&lt;void&gt;): void

Flushes data of a file to disk. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
1621 1622 1623 1624
  | Name     | Type                       | Mandatory  | Description             |
  | -------- | ------------------------- | ---- | --------------- |
  | fd       | number                    | Yes   | FD of the file.   |
  | Callback | AsyncCallback&lt;void&gt; | Yes   | Callback invoked when the file data is synchronized in asynchronous mode.|
A
Annie_wang 已提交
1625 1626 1627

**Error codes**

A
Annie_wang 已提交
1628
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath);
  fs.fsync(file.fd, (err) => {
    if (err) {
      console.info("fsync failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("fsync success");
      fs.closeSync(file);
    }
  });
  ```


## fs.fsyncSync

fsyncSync(fd: number): void

A
Annie_wang 已提交
1650
Flushes data of a file to disk synchronously.
A
Annie_wang 已提交
1651 1652 1653 1654 1655

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
1656 1657 1658
  | Name | Type    | Mandatory  | Description          |
  | ---- | ------ | ---- | ------------ |
  | fd   | number | Yes   | FD of the file.|
A
Annie_wang 已提交
1659 1660 1661

**Error codes**

A
Annie_wang 已提交
1662
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath);
  fs.fsyncSync(file.fd);
  fs.closeSync(file);
  ```

## fs.fdatasync

fdatasync(fd: number): Promise&lt;void&gt;

Flushes data of a file to disk. This API uses a promise to return the result. **fdatasync()** is similar to **fsync()**, but does not flush modified metadata unless that metadata is needed.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
1683 1684 1685
  | Name | Type    | Mandatory  | Description          |
  | ---- | ------ | ---- | ------------ |
  | fd   | number | Yes   | FD of the file.|
A
Annie_wang 已提交
1686 1687 1688

**Return value**

A
Annie_wang 已提交
1689 1690 1691
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
1692 1693 1694

**Error codes**

A
Annie_wang 已提交
1695
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath);
  fs.fdatasync(file.fd).then((err) => {
    console.info("Data flushed");
    fs.closeSync(file);
  }).catch((err) => {
    console.info("sync data failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.fdatasync

fdatasync(fd: number, callback: AsyncCallback&lt;void&gt;): void

Flushes data of a file to disk. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
1720 1721 1722 1723
  | Name     | Type                             | Mandatory  | Description               |
  | -------- | ------------------------------- | ---- | ----------------- |
  | fd       | number                          | Yes   | FD of the file.     |
  | callback | AsyncCallback&lt;void&gt; | Yes   | Callback invoked when the file data is synchronized in asynchronous mode.|
A
Annie_wang 已提交
1724 1725 1726

**Error codes**

A
Annie_wang 已提交
1727
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath);
  fs.fdatasync (file.fd, (err) => {
    if (err) {
      console.info("fdatasync failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("fdatasync success");
      fs.closeSync(file);
    }
  });
  ```

## fs.fdatasyncSync

fdatasyncSync(fd: number): void

A
Annie_wang 已提交
1748
Synchronizes data in a file synchronously.
A
Annie_wang 已提交
1749 1750 1751 1752 1753

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
1754 1755 1756
  | Name | Type    | Mandatory  | Description          |
  | ---- | ------ | ---- | ------------ |
  | fd   | number | Yes   | FD of the file.|
A
Annie_wang 已提交
1757 1758 1759

**Error codes**

A
Annie_wang 已提交
1760
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath);
  let stat = fs.fdatasyncSync(file.fd);
  fs.closeSync(file);
  ```

## fs.symlink

symlink(target: string, srcPath: string): Promise&lt;void&gt;

Creates a symbolic link based on a file path. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name | Type  | Mandatory| Description                        |
| ------- | ------ | ---- | ---------------------------- |
A
Annie_wang 已提交
1783 1784
| target  | string | Yes  | Application sandbox path of the source file.    |
| srcPath | string | Yes  | Application sandbox path of the symbolic link.|
A
Annie_wang 已提交
1785 1786 1787

**Return value**

A
Annie_wang 已提交
1788 1789 1790
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
1791 1792 1793

**Error codes**

A
Annie_wang 已提交
1794
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1795 1796 1797 1798 1799

**Example**

  ```js
  let srcFile = pathDir + "/test.txt";
A
Annie_wang 已提交
1800
  let dstFile = pathDir + "/test";
A
Annie_wang 已提交
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
  fs.symlink(srcFile, dstFile).then(() => {
      console.info("Symbolic link created");
  }).catch((err) => {
      console.info("symlink failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```


## fs.symlink
symlink(target: string, srcPath: string, callback: AsyncCallback&lt;void&gt;): void

Creates a symbolic link based on a file path. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type                     | Mandatory| Description                            |
| -------- | ------------------------- | ---- | -------------------------------- |
A
Annie_wang 已提交
1820 1821
| target   | string                    | Yes  | Application sandbox path of the source file.        |
| srcPath  | string                    | Yes  | Application sandbox path of the symbolic link.    |
A
Annie_wang 已提交
1822 1823
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked when the symbolic link is created asynchronously.|

A
Annie_wang 已提交
1824 1825
**Error codes**

A
Annie_wang 已提交
1826
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1827

A
Annie_wang 已提交
1828 1829 1830 1831
**Example**

  ```js
  let srcFile = pathDir + "/test.txt";
A
Annie_wang 已提交
1832
  let dstFile = pathDir + "/test";
A
Annie_wang 已提交
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
  fs.symlink(srcFile, dstFile, (err) => {
    if (err) {
      console.info("symlink failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("symlink success");
    }
  });
  ```

## fs.symlinkSync

symlinkSync(target: string, srcPath: string): void

Synchronously creates a symbolic link based on a file path.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name | Type  | Mandatory| Description                        |
| ------- | ------ | ---- | ---------------------------- |
A
Annie_wang 已提交
1854 1855
| target  | string | Yes  | Application sandbox path of the source file.    |
| srcPath | string | Yes  | Application sandbox path of the symbolic link.|
A
Annie_wang 已提交
1856

A
Annie_wang 已提交
1857 1858
**Error codes**

A
Annie_wang 已提交
1859
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1860

A
Annie_wang 已提交
1861 1862 1863 1864
**Example**

  ```js
  let srcFile = pathDir + "/test.txt";
A
Annie_wang 已提交
1865
  let dstFile = pathDir + "/test";
A
Annie_wang 已提交
1866 1867 1868
  fs.symlinkSync(srcFile, dstFile);
  ```

A
Annie_wang 已提交
1869 1870 1871 1872 1873
## fs.listFile
listFile(path: string, options?: {
    recursion?: boolean;
    listNum?: number;
    filter?: Filter;
A
Annie_wang 已提交
1874
}): Promise<string[]>
A
Annie_wang 已提交
1875

A
Annie_wang 已提交
1876
Lists all files in a folder. This API uses a promise to return the result.<br>This API supports recursive listing of all files (including files in subfolders) and file filtering.
A
Annie_wang 已提交
1877 1878 1879 1880 1881

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
1882 1883 1884 1885
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | path | string | Yes   | Application sandbox path of the folder.|
  | options | Object | No   | File filtering options. The files are not filtered by default.|
A
Annie_wang 已提交
1886 1887 1888

**options parameters**

A
Annie_wang 已提交
1889 1890
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
A
Annie_wang 已提交
1891
  | recursion | boolean | No   | Whether to list all files in subfolders recursively. The default value is **false**. If **recursion** is **false**, the names of the files and folders that meet the specified conditions in the current directory are returned. If **recursion** is **true**, the relative paths (starting with /) of all files that meet the specified conditions in the directory are returned.|
A
Annie_wang 已提交
1892 1893
  | listNum | number | No   | Number of file names to list. The default value **0** means to list all files.|
  | filter | [Filter](#filter) | No   | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.|
A
Annie_wang 已提交
1894 1895 1896

**Return value**

A
Annie_wang 已提交
1897 1898
  | Type                  | Description        |
  | --------------------- | ---------- |
A
Annie_wang 已提交
1899
  | Promise&lt;string[]&gt; | Promise used to return the file names listed.|
A
Annie_wang 已提交
1900 1901 1902

**Error codes**

A
Annie_wang 已提交
1903
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1904 1905 1906 1907 1908 1909 1910 1911 1912

**Example**

  ```js
  let options = {
    "recursion": false,
    "listNum": 0,
    "filter": {
      "suffix": [".png", ".jpg", ".jpeg"],
A
Annie_wang 已提交
1913
      "displayName": ["*abc", "efg*"],
A
Annie_wang 已提交
1914 1915 1916 1917 1918 1919
      "fileSizeOver": 1024,
      "lastModifiedAfter": new Date().getTime(),
    }
  };
  fs.listFile(pathDir, options).then((filenames) => {
    console.info("listFile succeed");
A
Annie_wang 已提交
1920
    for (let i = 0; i < filenames.length; i++) {
A
Annie_wang 已提交
1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
      console.info("fileName: %s", filenames[i]);
    }
  }).catch((err) => {
      console.info("list file failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.listFile
listFile(path: string, options?: {
    recursion?: boolean;
    listNum?: number;
    filter?: Filter;
A
Annie_wang 已提交
1933
}, callback: AsyncCallback<string[]>): void
A
Annie_wang 已提交
1934

A
Annie_wang 已提交
1935
Lists all files in a folder. This API uses an asynchronous callback to return the result.<br>This API supports recursive listing of all files (including files in subfolders) and file filtering.
A
Annie_wang 已提交
1936

A
Annie_wang 已提交
1937 1938
**System capability**: SystemCapability.FileManagement.File.FileIO

A
Annie_wang 已提交
1939 1940
**Parameters**

A
Annie_wang 已提交
1941 1942 1943 1944 1945
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | path | string | Yes   | Application sandbox path of the folder.|
  | options | Object | No   | File filtering options. The files are not filtered by default.|
  | callback | AsyncCallback&lt;string[]&gt; | Yes   | Callback invoked to return the file names listed.             |
A
Annie_wang 已提交
1946 1947 1948

**options parameters**

A
Annie_wang 已提交
1949 1950
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
A
Annie_wang 已提交
1951
  | recursion | boolean | No   | Whether to list all files in subfolders recursively. The default value is **false**. If **recursion** is **false**, the names of the files and folders that meet the specified conditions in the current directory are returned. If **recursion** is **true**, the relative paths (starting with /) of all files that meet the specified conditions in the directory are returned.|
A
Annie_wang 已提交
1952 1953
  | listNum | number | No   | Number of file names to list. The default value **0** means to list all files.|
  | filter | [Filter](#filter) | No   | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.|
A
Annie_wang 已提交
1954 1955 1956

**Error codes**

A
Annie_wang 已提交
1957
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
1958 1959 1960 1961 1962 1963 1964 1965 1966

**Example**

  ```js
  let options = {
    "recursion": false,
    "listNum": 0,
    "filter": {
      "suffix": [".png", ".jpg", ".jpeg"],
A
Annie_wang 已提交
1967
      "displayName": ["*abc", "efg*"],
A
Annie_wang 已提交
1968 1969 1970 1971 1972 1973 1974 1975 1976
      "fileSizeOver": 1024,
      "lastModifiedAfter": new Date().getTime(),
    }
  };
  fs.listFile(pathDir, options, (err, filenames) => {
    if (err) {
      console.info("list file failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("listFile succeed");
A
Annie_wang 已提交
1977
      for (let i = 0; i < filenames.length; i++) {
A
Annie_wang 已提交
1978 1979 1980 1981 1982 1983
        console.info("filename: %s", filenames[i]);
      }
    }
  });
  ```

A
Annie_wang 已提交
1984
## fs.listFileSync
A
Annie_wang 已提交
1985 1986 1987 1988 1989

listFileSync(path: string, options?: {
    recursion?: boolean;
    listNum?: number;
    filter?: Filter;
A
Annie_wang 已提交
1990
}): string[]
A
Annie_wang 已提交
1991

A
Annie_wang 已提交
1992
Lists all files in a folder synchronously. This API supports recursive listing of all files (including files in subfolders) and file filtering.
A
Annie_wang 已提交
1993

A
Annie_wang 已提交
1994 1995
**System capability**: SystemCapability.FileManagement.File.FileIO

A
Annie_wang 已提交
1996 1997
**Parameters**

A
Annie_wang 已提交
1998 1999 2000 2001
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | path | string | Yes   | Application sandbox path of the folder.|
  | options | Object | No   | File filtering options. The files are not filtered by default.|
A
Annie_wang 已提交
2002 2003 2004

**options parameters**

A
Annie_wang 已提交
2005 2006
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
A
Annie_wang 已提交
2007
  | recursion | boolean | No   | Whether to list all files in subfolders recursively. The default value is **false**. If **recursion** is **false**, the names of the files and folders that meet the specified conditions in the current directory are returned. If **recursion** is **true**, the relative paths (starting with /) of all files that meet the specified conditions in the directory are returned.|
A
Annie_wang 已提交
2008 2009
  | listNum | number | No   | Number of file names to list. The default value **0** means to list all files.|
  | filter | [Filter](#filter) | No   | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.|
A
Annie_wang 已提交
2010 2011 2012

**Return value**

A
Annie_wang 已提交
2013 2014 2015
  | Type                  | Description        |
  | --------------------- | ---------- |
  | string[] | File names listed.|
A
Annie_wang 已提交
2016 2017 2018

**Error codes**

A
Annie_wang 已提交
2019
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2020 2021 2022 2023 2024 2025 2026 2027 2028

**Example**

  ```js
  let options = {
    "recursion": false,
    "listNum": 0,
    "filter": {
      "suffix": [".png", ".jpg", ".jpeg"],
A
Annie_wang 已提交
2029
      "displayName": ["*abc", "efg*"],
A
Annie_wang 已提交
2030 2031 2032 2033 2034 2035
      "fileSizeOver": 1024,
      "lastModifiedAfter": new Date().getTime(),
    }
  };
  let filenames = fs.listFileSync(pathDir, options);
  console.info("listFile succeed");
A
Annie_wang 已提交
2036
  for (let i = 0; i < filenames.length; i++) {
A
Annie_wang 已提交
2037 2038 2039
    console.info("filename: %s", filenames[i]);
  }
  ```
A
Annie_wang 已提交
2040 2041 2042 2043 2044

## fs.moveDir<sup>10+</sup>

moveDir(src: string, dest: string, mode?: number): Promise\<void>

A
Annie_wang 已提交
2045
Moves a directory. This API uses a promise to return the result.
A
Annie_wang 已提交
2046 2047 2048 2049 2050

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2051 2052 2053 2054
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | src | string | Yes   | Application sandbox path of the directory to move.|
  | dest | string | Yes   | Application sandbox path of the destination directory.|
A
Annie_wang 已提交
2055
  | mode | number | No   | Mode for moving the directory. The default value is **0**.<br>- **0**: Throw an exception if a directory conflict occurs.<br>Throw an exception if there is a non-empty directory with the same name in the destination directory.<br>- **1**: Throw an exception if a file conflict occurs.<br>Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles10)> format.<br>- **2**: Forcibly overwrite the conflicting files in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.<br>- **3**: Forcibly overwrite the conflicting directory.<br>Move the source directory to the destination directory and overwrite the conflicting directory completely. That is, if there is a directory with the same name in the destination directory, all the original files in that directory will not be retained.|
A
Annie_wang 已提交
2056 2057 2058

**Return value**

A
Annie_wang 已提交
2059 2060 2061
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
2062 2063 2064

**Error codes**

A
Annie_wang 已提交
2065
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2066 2067 2068 2069

**Example**

  ```js
A
Annie_wang 已提交
2070
  // move directory from srcPath to destPath
A
Annie_wang 已提交
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
  let srcPath = pathDir + "/srcDir/";
  let destPath = pathDir + "/destDir/";
  fs.moveDir(srcPath, destPath, 1).then(() => {
      console.info("move directory succeed");
  }).catch((err) => {
    if (err.code == 13900015) {
      for (let i = 0; i < err.data.length; i++) {
        console.info("move directory failed with conflicting files: " + err.data[i].srcFile +
          " " + err.data[i].destFile);
      }
    } else {
      console.info("move directory failed with error message: " + err.message + ", error code: " + err.code);
    }
  });
  ```

## fs.moveDir<sup>10+</sup>

A
Annie_wang 已提交
2089
moveDir(src: string, dest: string, mode?: number, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void
A
Annie_wang 已提交
2090

A
Annie_wang 已提交
2091
Moves a directory. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
2092 2093 2094 2095 2096

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2097 2098 2099 2100
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | src | string | Yes   | Application sandbox path of the source directory.|
  | dest | string | Yes   | Application sandbox path of the destination directory.|
A
Annie_wang 已提交
2101 2102
  | mode | number | No   | Mode for moving the directory. The default value is **0**.<br>- **0**: Throw an exception if a directory conflict occurs.<br>Throw an exception if there is a directory with the same name in the destination directory.<br>- **1**: Throw an exception if a file conflict occurs.<br>Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles10)> format.<br>- **2**: Forcibly overwrite the conflicting files in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.<br>- **3**: Forcibly overwrite the conflicting directory.<br>Move the source directory to the destination directory and overwrite the conflicting directory completely. That is, if there is a directory with the same name in the destination directory, all the original files in that directory will not be retained.|
  | callback | AsyncCallback&lt;void, Array&lt;[ConflictFiles](#conflictfiles10)&gt;&gt; | Yes   | Callback invoked when the directory is moved.             |
A
Annie_wang 已提交
2103 2104 2105

**Error codes**

A
Annie_wang 已提交
2106
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2107 2108 2109 2110

**Example**

  ```js
A
Annie_wang 已提交
2111
  // move directory from srcPath to destPath
A
Annie_wang 已提交
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127
  let srcPath = pathDir + "/srcDir/";
  let destPath = pathDir + "/destDir/";
  fs.moveDir(srcPath, destPath, 1, (err) => {
    if (err && err.code == 13900015) {
      for (let i = 0; i < err.data.length; i++) {
        console.info("move directory failed with conflicting files: " + err.data[i].srcFile +
          " " + err.data[i].destFile);
      }
    } else if (err) {
      console.info("move directory failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("move directory succeed");
    }  
  });
  ```

A
Annie_wang 已提交
2128
## fs.moveFile
A
Annie_wang 已提交
2129

A
Annie_wang 已提交
2130
moveFile(src: string, dest: string, mode?: number): Promise\<void>
A
Annie_wang 已提交
2131 2132 2133 2134 2135 2136 2137

Moves a file. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2138 2139 2140 2141 2142
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | src | string | Yes   | Application sandbox path of the source file.|
  | dest | string | Yes   | Application sandbox path of the destination file.|
  | mode | number | No   | Whether to overwrite the file with the same name in the destination directory.<br>The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception.<br>The default value is **0**.|
A
Annie_wang 已提交
2143

A
Annie_wang 已提交
2144 2145
**Return value**

A
Annie_wang 已提交
2146 2147 2148
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
2149 2150 2151

**Error codes**

A
Annie_wang 已提交
2152
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2153

A
Annie_wang 已提交
2154 2155 2156
**Example**

  ```js
A
Annie_wang 已提交
2157 2158
  let srcPath = pathDir + "/source.txt";
  let destPath = pathDir + "/dest.txt";
A
Annie_wang 已提交
2159 2160 2161 2162 2163 2164 2165
  fs.moveFile(srcPath, destPath, 0).then(() => {
      console.info("move file succeed");
  }).catch((err) => {
      console.info("move file failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

A
Annie_wang 已提交
2166
## fs.moveFile
A
Annie_wang 已提交
2167

A
Annie_wang 已提交
2168
moveFile(src: string, dest: string, mode?: number, callback: AsyncCallback\<void>): void
A
Annie_wang 已提交
2169 2170 2171 2172 2173 2174 2175

Moves a file. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2176 2177 2178 2179
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | src | string | Yes   | Application sandbox path of the source file.|
  | dest | string | Yes   | Application sandbox path of the destination file.|
A
Annie_wang 已提交
2180
  | mode | number | No   | Whether to overwrite the file with the same name in the destination directory.<br>The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception.<br>The default value is **0**.|
A
Annie_wang 已提交
2181
  | callback | AsyncCallback&lt;void&gt; | Yes   | Callback invoked when the file is moved.             |
A
Annie_wang 已提交
2182 2183 2184

**Error codes**

A
Annie_wang 已提交
2185
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2186 2187 2188 2189

**Example**

  ```js
A
Annie_wang 已提交
2190 2191
  let srcPath = pathDir + "/source.txt";
  let destPath = pathDir + "/dest.txt";
A
Annie_wang 已提交
2192 2193 2194 2195 2196 2197 2198 2199 2200
  fs.moveFile(srcPath, destPath, 0, (err) => {
    if (err) {
      console.info("move file failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("move file succeed");
    }  
  });
  ```

A
Annie_wang 已提交
2201
## fs.moveFileSync
A
Annie_wang 已提交
2202

A
Annie_wang 已提交
2203
moveFileSync(src: string, dest: string, mode?: number): void
A
Annie_wang 已提交
2204 2205 2206 2207 2208 2209 2210

Moves a file synchronously.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2211 2212 2213 2214
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | src | string | Yes   | Application sandbox path of the source file.|
  | dest | string | Yes   | Application sandbox path of the destination file.|
A
Annie_wang 已提交
2215
  | mode | number | No   | Whether to overwrite the file with the same name in the destination directory.<br>The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception.<br>The default value is **0**.|
A
Annie_wang 已提交
2216 2217 2218

**Error codes**

A
Annie_wang 已提交
2219
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2220 2221 2222 2223

**Example**

  ```js
A
Annie_wang 已提交
2224 2225
  let srcPath = pathDir + "/source.txt";
  let destPath = pathDir + "/dest.txt";
A
Annie_wang 已提交
2226 2227 2228 2229
  fs.moveFileSync(srcPath, destPath, 0);
  console.info("move file succeed");
  ```

A
Annie_wang 已提交
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
## fs.mkdtemp

mkdtemp(prefix: string): Promise&lt;string&gt;

Creates a temporary directory. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2240 2241 2242
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | prefix | string | Yes   | A randomly generated string used to replace "XXXXXX" in a directory.|
A
Annie_wang 已提交
2243 2244 2245

**Return value**

A
Annie_wang 已提交
2246 2247
  | Type                  | Description        |
  | --------------------- | ---------- |
A
Annie_wang 已提交
2248
  | Promise&lt;string&gt; | Promise used to return the directory created.|
A
Annie_wang 已提交
2249 2250 2251

**Error codes**

A
Annie_wang 已提交
2252
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273

**Example**

  ```js
  fs.mkdtemp(pathDir + "/XXXXXX").then((pathDir) => {
      console.info("mkdtemp succeed:" + pathDir);
  }).catch((err) => {
      console.info("mkdtemp failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.mkdtemp

mkdtemp(prefix: string, callback: AsyncCallback&lt;string&gt;): void

Creates a temporary directory. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2274 2275 2276 2277
  | Name     | Type                         | Mandatory  | Description                         |
  | -------- | --------------------------- | ---- | --------------------------- |
  | prefix   | string                      | Yes   | A randomly generated string used to replace "XXXXXX" in a directory.|
  | callback | AsyncCallback&lt;string&gt; | Yes   | Callback invoked when a temporary directory is created asynchronously.             |
A
Annie_wang 已提交
2278 2279 2280

**Error codes**

A
Annie_wang 已提交
2281
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304

**Example**

  ```js
  fs.mkdtemp(pathDir + "/XXXXXX", (err, res) => {
    if (err) {
      console.info("mkdtemp failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("mkdtemp success");
    }
  });
  ```

## fs.mkdtempSync

mkdtempSync(prefix: string): string

Synchronously creates a temporary directory.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2305 2306 2307
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | prefix | string | Yes   | A randomly generated string used to replace "XXXXXX" in a directory.|
A
Annie_wang 已提交
2308 2309 2310

**Return value**

A
Annie_wang 已提交
2311 2312 2313
  | Type   | Description        |
  | ------ | ---------- |
  | string | Unique path generated.|
A
Annie_wang 已提交
2314 2315 2316

**Error codes**

A
Annie_wang 已提交
2317
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2318 2319 2320 2321 2322

**Example**

  ```js
  let res = fs.mkdtempSync(pathDir + "/XXXXXX");
A
Annie_wang 已提交
2323
  ```  
A
Annie_wang 已提交
2324

A
Annie_wang 已提交
2325 2326 2327

## fs.createRandomAccessFile<sup>10+</sup>

A
Annie_wang 已提交
2328
createRandomAccessFile(file: string|File, mode?: number): Promise&lt;RandomAccessFile&gt;
A
Annie_wang 已提交
2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356

Creates a **RandomAccessFile** instance based on the specified file path or file object. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**
|    Name   | Type    | Mandatory  | Description                         |
| ------------ | ------ | ------ | ------------------------------------------------------------ |
|     file     | string\|[File](#file) | Yes   | Application sandbox path of the file or an opened file object.|
|     mode     | number | No  | [Option](#openmode) for creating the **RandomAccessFile** instance. This parameter is valid only when the application sandbox path of the file is passed in. One of the following options must be specified:<br>- **OpenMode.READ_ONLY(0o0)**: Create the file in read-only mode. This is the default value.<br>- **OpenMode.WRITE_ONLY(0o1)**: Create the file in write-only mode.<br>- **OpenMode.READ_WRITE(0o2)**: Create the file in read/write mode.<br>You can also specify the following options, separated by a bitwise OR operator (&#124;). By default, no additional options are given.<br>- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.<br>- **OpenMode.TRUNC(0o1000)**: If the **RandomAccessFile** object already exists and is created in write-only or read/write mode, truncate the file length to 0.<br>- **OpenMode.APPEND(0o2000)**: Create the file in append mode. New data will be added to the end of the **RandomAccessFile** object. <br>- **OpenMode.NONBLOCK(0o4000)**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the created file and in subsequent I/Os.<br>- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.<br>- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.<br>- **OpenMode.SYNC(0o4010000)**: Create a **RandomAccessFile** instance in synchronous I/O mode.|

**Return value**

  | Type                               | Description       |
  | --------------------------------- | --------- |
  | Promise&lt;[RandomAccessFile](#randomaccessfile)&gt; | Promise used to return the **RandomAccessFile** instance created.|

**Error codes**

For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
  fs.createRandomAccessFile(file).then((randomAccessFile) => {
      console.info("randomAccessFile fd: " + randomAccessFile.fd);
A
Annie_wang 已提交
2357 2358
      randomAccessFile.close();
      fs.closeSync(file);
A
Annie_wang 已提交
2359 2360 2361 2362 2363 2364 2365 2366
  }).catch((err) => {
      console.info("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```


## fs.createRandomAccessFile<sup>10+</sup>

A
Annie_wang 已提交
2367
createRandomAccessFile(file: string|File, mode?: number, callback: AsyncCallback&lt;RandomAccessFile&gt;): void
A
Annie_wang 已提交
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393

Creates a **RandomAccessFile** instance based on the specified file path or file object. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

|  Name   | Type    | Mandatory  | Description                         |
| ------------ | ------ | ------ | ------------------------------------------------------------ |
|     file     | string\|[File](#file) | Yes   | Application sandbox path of the file or an opened file object.|
|     mode     | number | No  | [Option](#openmode) for creating the **RandomAccessFile** instance. This parameter is valid only when the application sandbox path of the file is passed in. One of the following options must be specified:<br>- **OpenMode.READ_ONLY(0o0)**: Create the file in read-only mode. This is the default value.<br>- **OpenMode.WRITE_ONLY(0o1)**: Create the file in write-only mode.<br>- **OpenMode.READ_WRITE(0o2)**: Create the file in read/write mode.<br>You can also specify the following options, separated by a bitwise OR operator (&#124;). By default, no additional options are given.<br>- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.<br>- **OpenMode.TRUNC(0o1000)**: If the **RandomAccessFile** object already exists and is created in write-only or read/write mode, truncate the file length to 0.<br>- **OpenMode.APPEND(0o2000)**: Create the file in append mode. New data will be added to the end of the **RandomAccessFile** object. <br>- **OpenMode.NONBLOCK(0o4000)**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the created file and in subsequent I/Os.<br>- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.<br>- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.<br>- **OpenMode.SYNC(0o4010000)**: Create a **RandomAccessFile** instance in synchronous I/O mode.|
| callback | AsyncCallback&lt;[RandomAccessFile](#randomaccessfile)&gt; | Yes  | Callback invoked to return the **RandomAccessFile** instance created.                                  |

**Error codes**

For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).

**Example**
  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
  fs.createRandomAccessFile(file, (err, randomAccessFile) => {
      if (err) {
          console.info("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code);
      } else {
          console.info("randomAccessFilefile fd: " + randomAccessFile.fd);
A
Annie_wang 已提交
2394 2395
          randomAccessFile.close();
          fs.closeSync(file);
A
Annie_wang 已提交
2396 2397 2398 2399 2400 2401 2402
      }
  });
  ```


## fs.createRandomAccessFileSync<sup>10+</sup>

A
Annie_wang 已提交
2403
createRandomAccessFileSync(file: string|File, mode?: number): RandomAccessFile
A
Annie_wang 已提交
2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429

Creates a **RandomAccessFile** instance based on the specified file path or file object.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

|  Name   | Type    | Mandatory  | Description                         |
| ------------ | ------ | ------ | ------------------------------------------------------------ |
|     file     | string\|[File](#file) | Yes   | Application sandbox path of the file or an opened file object.|
|     mode     | number | No  | [Option](#openmode) for creating the **RandomAccessFile** instance. This parameter is valid only when the application sandbox path of the file is passed in. One of the following options must be specified:<br>- **OpenMode.READ_ONLY(0o0)**: Create the file in read-only mode. This is the default value.<br>- **OpenMode.WRITE_ONLY(0o1)**: Create the file in write-only mode.<br>- **OpenMode.READ_WRITE(0o2)**: Create the file in read/write mode.<br>You can also specify the following options, separated by a bitwise OR operator (&#124;). By default, no additional options are given.<br>- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.<br>- **OpenMode.TRUNC(0o1000)**: If the **RandomAccessFile** object already exists and is created in write-only or read/write mode, truncate the file length to 0.<br>- **OpenMode.APPEND(0o2000)**: Create the file in append mode. New data will be added to the end of the **RandomAccessFile** object. <br>- **OpenMode.NONBLOCK(0o4000)**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the created file and in subsequent I/Os.<br>- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.<br>- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.<br>- **OpenMode.SYNC(0o4010000)**: Create a **RandomAccessFile** instance in synchronous I/O mode.|

**Return value**

  | Type               | Description       |
  | ------------------ | --------- |
  | [RandomAccessFile](#randomaccessfile) | **RandomAccessFile** instance created.|

**Error codes**

For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
A
Annie_wang 已提交
2430 2431 2432 2433
  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
  let randomaccessfile = fs.createRandomAccessFileSync(file);
  randomaccessfile.close();
  fs.closeSync(file);
A
Annie_wang 已提交
2434 2435
  ```

A
Annie_wang 已提交
2436 2437 2438 2439
## fs.createStream

createStream(path: string, mode: string): Promise&lt;Stream&gt;

A
Annie_wang 已提交
2440
Creates a stream based on the file path. This API uses a promise to return the result.
A
Annie_wang 已提交
2441 2442 2443 2444 2445 2446 2447

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                                                        |
| ------ | ------ | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
2448
| path   | string | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
2449 2450 2451 2452
| mode   | string | Yes  | - **r**: Open a file for reading. The file must exist.<br>- **r+**: Open a file for both reading and writing. The file must exist.<br>- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).|

**Return value**

A
Annie_wang 已提交
2453 2454
  | Type                               | Description       |
  | --------------------------------- | --------- |
A
Annie_wang 已提交
2455
  | Promise&lt;[Stream](#stream)&gt; | Promise used to return the stream opened.|
A
Annie_wang 已提交
2456 2457 2458

**Error codes**

A
Annie_wang 已提交
2459
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  fs.createStream(filePath, "r+").then((stream) => {
      console.info("Stream created");
  }).catch((err) => {
      console.info("createStream failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```


## fs.createStream

createStream(path: string, mode: string, callback: AsyncCallback&lt;Stream&gt;): void

A
Annie_wang 已提交
2477
Creates a stream based on the file path. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
2478 2479 2480 2481 2482 2483 2484

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name  | Type                                   | Mandatory| Description                                                        |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
2485
| path     | string                                  | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
2486
| mode     | string                                  | Yes  | - **r**: Open a file for reading. The file must exist.<br>- **r+**: Open a file for both reading and writing. The file must exist.<br>- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).|
A
Annie_wang 已提交
2487
| callback | AsyncCallback&lt;[Stream](#stream)&gt; | Yes  | Callback invoked when the stream is created asynchronously.                                  |
A
Annie_wang 已提交
2488

A
Annie_wang 已提交
2489 2490
**Error codes**

A
Annie_wang 已提交
2491
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2492

A
Annie_wang 已提交
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  fs.createStream(filePath, "r+", (err, stream) => {
    if (err) {
      console.info("create stream failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("create stream success");
    }
  });
  ```

## fs.createStreamSync

createStreamSync(path: string, mode: string): Stream

A
Annie_wang 已提交
2510
Synchronously creates a stream based on the file path.
A
Annie_wang 已提交
2511 2512 2513 2514 2515 2516 2517

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

| Name| Type  | Mandatory| Description                                                        |
| ------ | ------ | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
2518
| path   | string | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
2519 2520 2521 2522
| mode   | string | Yes  | - **r**: Open a file for reading. The file must exist.<br>- **r+**: Open a file for both reading and writing. The file must exist.<br>- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).|

**Return value**

A
Annie_wang 已提交
2523 2524 2525
  | Type               | Description       |
  | ------------------ | --------- |
  | [Stream](#stream) | Stream opened.|
A
Annie_wang 已提交
2526 2527 2528

**Error codes**

A
Annie_wang 已提交
2529
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let ss = fs.createStreamSync(filePath, "r+");
  ```


## fs.fdopenStream

fdopenStream(fd: number, mode: string): Promise&lt;Stream&gt;

A
Annie_wang 已提交
2543
Opens a stream based on the file descriptor. This API uses a promise to return the result.
A
Annie_wang 已提交
2544 2545 2546 2547 2548

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2549 2550 2551 2552
  | Name | Type    | Mandatory  | Description                                      |
  | ---- | ------ | ---- | ---------------------------------------- |
  | fd   | number | Yes   | FD of the file.                            |
  | mode | string | Yes   | - **r**: Open a file for reading. The file must exist.<br>- **r+**: Open a file for both reading and writing. The file must exist.<br>- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).|
A
Annie_wang 已提交
2553 2554 2555

**Return value**

A
Annie_wang 已提交
2556 2557
  | Type                              | Description       |
  | --------------------------------- | --------- |
A
Annie_wang 已提交
2558
  | Promise&lt;[Stream](#stream)&gt; | Promise used to return the stream opened.|
A
Annie_wang 已提交
2559 2560 2561

**Error codes**

A
Annie_wang 已提交
2562
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath);
  fs.fdopenStream(file.fd, "r+").then((stream) => {
      console.info("Stream opened");
      fs.closeSync(file);
  }).catch((err) => {
      console.info("openStream failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

## fs.fdopenStream

fdopenStream(fd: number, mode: string, callback: AsyncCallback&lt;Stream&gt;): void

A
Annie_wang 已提交
2581
Opens a stream based on the file descriptor. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
2582 2583 2584 2585 2586

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2587 2588 2589 2590
  | Name     | Type                                      | Mandatory  | Description                                      |
  | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
  | fd       | number                                   | Yes   | FD of the file.                            |
  | mode     | string                                   | Yes   | - **r**: Open a file for reading. The file must exist.<br>- **r+**: Open a file for both reading and writing. The file must exist.<br>- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).|
A
Annie_wang 已提交
2591
  | callback | AsyncCallback&lt;[Stream](#stream)&gt; | Yes   | Callback invoked when the stream is created asynchronously.                           |
A
Annie_wang 已提交
2592 2593 2594

**Error codes**

A
Annie_wang 已提交
2595
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
  fs.fdopenStream(file.fd, "r+", (err, stream) => {
    if (err) {
      console.info("fdopen stream failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("fdopen stream success");
      fs.closeSync(file);
    }
  });
  ```

## fs.fdopenStreamSync

fdopenStreamSync(fd: number, mode: string): Stream

A
Annie_wang 已提交
2616
Synchronously opens a stream based on the file descriptor.
A
Annie_wang 已提交
2617 2618 2619 2620 2621

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2622 2623 2624 2625
  | Name | Type    | Mandatory  | Description                                      |
  | ---- | ------ | ---- | ---------------------------------------- |
  | fd   | number | Yes   | FD of the file.                            |
  | mode | string | Yes   | - **r**: Open a file for reading. The file must exist.<br>- **r+**: Open a file for both reading and writing. The file must exist.<br>- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).|
A
Annie_wang 已提交
2626 2627 2628

**Return value**

A
Annie_wang 已提交
2629 2630 2631
  | Type               | Description       |
  | ------------------ | --------- |
  | [Stream](#stream) | Stream opened.|
A
Annie_wang 已提交
2632 2633 2634

**Error codes**

A
Annie_wang 已提交
2635
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2636 2637 2638 2639 2640 2641 2642 2643 2644 2645

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE);
  let ss = fs.fdopenStreamSync(file.fd, "r+");
  fs.closeSync(file);
  ```

A
Annie_wang 已提交
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657
## fs.createWatcher<sup>10+</sup>

createWatcher(path: string, events: number, listener: WatchEventListener): Watcher

Creates a **Watcher** object to observe file or directory changes.

**System API**: This is a system API.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2658 2659 2660
  | Name | Type    | Mandatory  | Description                                      |
  | ---- | ------ | ---- | ---------------------------------------- |
  | path   | string | Yes   | Application sandbox path of the file or directory to observe.                            |
A
Annie_wang 已提交
2661
  | events | number | Yes   | Events to observe. Multiple events can be separated by a bitwise OR operator (&#124;).<br>- **0x1: IN_ACCESS**: A file is accessed.<br>- **0x2: IN_MODIFY**: The file content is modified.<br>- **0x4: IN_ATTRIB**: Metadata is modified.<br>- **0x8: IN_CLOSE_WRITE**: The file opened for writing is closed.<br>- **0x10: IN_CLOSE_NOWRITE**: The file or directory opened is closed without being written.<br>- **0x20: IN_OPEN**: A file or directory is opened.<br>- **0x40: IN_MOVED_FROM**: A file in the observed directory is moved.<br>- **0x80: IN_MOVED_TO**: A file is moved to the observed directory.<br>- **0x100: IN_CREATE**: A file or directory is created in the observed directory.<br>- **0x200: IN_DELETE**: A file or directory is deleted from the observed directory.<br>- **0x400: IN_DELETE_SELF**: The observed directory is deleted. After the directory is deleted, the listening stops.<br>- **0x800: IN_MOVE_SELF**: The observed file or directory is moved. After the file or directory is moved, the listening continues.<br>- **0xfff: IN_ALL_EVENTS**: All events.|
A
Annie_wang 已提交
2662
  | listener   | WatchEventListener | Yes   | Callback invoked when an observed event occurs. The callback will be invoked each time an observed event occurs.                            |
A
Annie_wang 已提交
2663 2664 2665

**Return value**

A
Annie_wang 已提交
2666 2667 2668
  | Type               | Description       |
  | ------------------ | --------- |
  | [Watcher](#watcher10) | **Watcher** object created.|
A
Annie_wang 已提交
2669 2670 2671

**Error codes**

A
Annie_wang 已提交
2672
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  let watcher = fs.createWatcher(filePath, 0x2 | 0x10, (watchEvent) => {
    if (watchEvent.event == 0x2) {
      console.info(watchEvent.fileName + 'was modified');
    } else if (watchEvent.event == 0x10) {
      console.info(watchEvent.fileName + 'was closed');
    }
  });
  watcher.start();
  fs.writeSync(file.fd, 'test');
  fs.closeSync(file);
  watcher.stop();
  ```

## WatchEventListener<sup>10+</sup>

(event: WatchEvent): void

Called when an observed event occurs.

**System API**: This is a system API.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2704 2705 2706 2707
  | Name | Type    | Mandatory  | Description                                      |
  | ---- | ------ | ---- | ---------------------------------------- |
  | event   | WatchEvent | Yes   | Event for the callback to invoke.                            |
 
A
Annie_wang 已提交
2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721
## WatchEvent<sup>10+</sup>

Defines the event to observe.

**System API**: This is a system API.

**System capability**: SystemCapability.FileManagement.File.FileIO

| Name  | Type  | Readable  | Writable  | Description     |
| ---- | ------ | ---- | ---- | ------- |
| fileName | string | Yes   | No   | Name of the file for which the event occurs.|
| event | number | Yes   | No   | Events to observe. For details, see **events** in [createWatcher](#fscreatewatcher10).|
| cookie | number | Yes   | No   | Cookie bound with the event. Currently, only the **IN_MOVED_FROM** and **IN_MOVED_TO** events are supported. The **IN_MOVED_FROM** and **IN_MOVED_TO** events of the same file have the same **cookie** value.|

A
Annie_wang 已提交
2722 2723 2724 2725 2726 2727 2728 2729 2730
## Stat

Represents detailed file information. Before calling any API of the **Stat()** class, use [stat()](#fsstat) to create a **Stat** instance synchronously or asynchronously.

**System capability**: SystemCapability.FileManagement.File.FileIO

### Attributes

| Name    | Type  | Readable  | Writable  | Description                                      |
A
Annie_wang 已提交
2731
| ------ | ------ | ---- | ---- | ---------------------------------------- |                        
A
Annie_wang 已提交
2732
| ino    | number | Yes   | No   | File ID. Different files on the same device have different **ino**s.|                 |
A
Annie_wang 已提交
2733
| mode   | number | Yes   | No   | File permissions. The meaning of each bit is as follows:<br>**NOTE**<br>The following values are in octal format. The returned values are in decimal format. You need to convert the values.<br>- **0o400**: The owner has the permission to read a regular file or a directory entry.<br>- **0o200**: The owner has the permission to write a regular file or create and delete a directory entry.<br>- **0o100**: The owner has the permission to execute a regular file or search for the specified path in a directory.<br>- **0o040**: The user group has the permission to read a regular file or a directory entry.<br>- **0o020**: The user group has the permission to write a regular file or create and delete a directory entry.<br>- **0o010**: The user group has the permission to execute a regular file or search for the specified path in a directory.<br>- **0o004**: Other users have the permission to read a regular file or a directory entry.<br>- **0o002**: Other users have the permission to write a regular file or create and delete a directory entry.<br>- **0o001**: Other users have the permission to execute a regular file or search for the specified path in a directory.|
A
Annie_wang 已提交
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
| uid    | number | Yes   | No   | ID of the file owner.|
| gid    | number | Yes   | No   | ID of the user group of the file.|
| size   | number | Yes   | No   | File size, in bytes. This parameter is valid only for regular files. |
| atime  | number | Yes   | No   | Time of the last access to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.       |
| mtime  | number | Yes   | No   | Time of the last modification to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.       |
| ctime  | number | Yes   | No   | Time of the last status change of the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.     |

### isBlockDevice

isBlockDevice(): boolean

Checks whether this file is a block special file. A block special file supports access by block only, and it is cached when accessed.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Return value**

A
Annie_wang 已提交
2751 2752 2753
  | Type     | Description              |
  | ------- | ---------------- |
  | boolean | Whether the file is a block special file.|
A
Annie_wang 已提交
2754 2755 2756

**Error codes**

A
Annie_wang 已提交
2757
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let isBLockDevice = fs.statSync(filePath).isBlockDevice();
  ```

### isCharacterDevice

isCharacterDevice(): boolean

Checks whether this file is a character special file. A character special file supports random access, and it is not cached when accessed.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Return value**

A
Annie_wang 已提交
2776 2777 2778
  | Type     | Description               |
  | ------- | ----------------- |
  | boolean | Whether the file is a character special file.|
A
Annie_wang 已提交
2779 2780 2781

**Error codes**

A
Annie_wang 已提交
2782
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let isCharacterDevice = fs.statSync(filePath).isCharacterDevice();
  ```

### isDirectory

isDirectory(): boolean

Checks whether this file is a directory.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Return value**

A
Annie_wang 已提交
2801 2802 2803
  | Type     | Description           |
  | ------- | ------------- |
  | boolean | Whether the file is a directory.|
A
Annie_wang 已提交
2804 2805 2806

**Error codes**

A
Annie_wang 已提交
2807
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825

**Example**

  ```js
  let dirPath = pathDir + "/test";
  let isDirectory = fs.statSync(dirPath).isDirectory(); 
  ```

### isFIFO

isFIFO(): boolean

Checks whether this file is a named pipe (or FIFO). Named pipes are used for inter-process communication.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Return value**

A
Annie_wang 已提交
2826 2827
  | Type     | Description                   |
  | ------- | --------------------- |
A
Annie_wang 已提交
2828
  | boolean | Whether the file is an FIFO.|
A
Annie_wang 已提交
2829 2830 2831

**Error codes**

A
Annie_wang 已提交
2832
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let isFIFO = fs.statSync(filePath).isFIFO(); 
  ```

### isFile

isFile(): boolean

Checks whether this file is a regular file.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Return value**

A
Annie_wang 已提交
2851 2852 2853
  | Type     | Description             |
  | ------- | --------------- |
  | boolean | Whether the file is a regular file.|
A
Annie_wang 已提交
2854 2855 2856

**Error codes**

A
Annie_wang 已提交
2857
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let isFile = fs.statSync(filePath).isFile();
  ```

### isSocket

isSocket(): boolean

Checks whether this file is a socket.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Return value**

A
Annie_wang 已提交
2876 2877 2878
  | Type     | Description            |
  | ------- | -------------- |
  | boolean | Whether the file is a socket.|
A
Annie_wang 已提交
2879 2880 2881

**Error codes**

A
Annie_wang 已提交
2882
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let isSocket = fs.statSync(filePath).isSocket(); 
  ```

### isSymbolicLink

isSymbolicLink(): boolean

Checks whether this file is a symbolic link.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Return value**

A
Annie_wang 已提交
2901 2902 2903
  | Type     | Description             |
  | ------- | --------------- |
  | boolean | Whether the file is a symbolic link.|
A
Annie_wang 已提交
2904 2905 2906

**Error codes**

A
Annie_wang 已提交
2907
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2908 2909 2910 2911 2912 2913 2914 2915 2916 2917

**Example**

  ```js
  let filePath = pathDir + "/test";
  let isSymbolicLink = fs.statSync(filePath).isSymbolicLink(); 
  ```

## Stream

A
Annie_wang 已提交
2918
Provides a stream for file operations. Before calling any API of the **Stream** class, use **createStream()** to create a **Stream** instance synchronously or asynchronously.
A
Annie_wang 已提交
2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929

### close

close(): Promise&lt;void&gt;

Closes the stream. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Return value**

A
Annie_wang 已提交
2930 2931
  | Type                 | Description           |
  | ------------------- | ------------- |
A
Annie_wang 已提交
2932
  | Promise&lt;void&gt; | Promise used to return the result.|
A
Annie_wang 已提交
2933 2934 2935

**Error codes**

A
Annie_wang 已提交
2936
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let ss= fs.createStreamSync(filePath, "r+");
  ss.close().then(() => {
      console.info("File stream closed");
  }).catch((err) => {
      console.info("close fileStream  failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

### close

close(callback: AsyncCallback&lt;void&gt;): void

Closes the stream. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
2960 2961 2962
  | Name     | Type                       | Mandatory  | Description           |
  | -------- | ------------------------- | ---- | ------------- |
  | callback | AsyncCallback&lt;void&gt; | Yes   | Callback invoked immediately after the stream is closed.|
A
Annie_wang 已提交
2963 2964 2965

**Error codes**

A
Annie_wang 已提交
2966
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2967 2968 2969 2970 2971 2972 2973 2974 2975 2976

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let ss= fs.createStreamSync(filePath, "r+");
  ss.close((err) => {
    if (err) {
      console.info("close stream failed with error message: " + err.message + ", error code: " + err.code);
    } else {
A
Annie_wang 已提交
2977
      console.info("close stream success");
A
Annie_wang 已提交
2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989
    }
  });
  ```

### closeSync

closeSync(): void

Synchronously closes the stream.

**System capability**: SystemCapability.FileManagement.File.FileIO

A
Annie_wang 已提交
2990 2991
**Error codes**

A
Annie_wang 已提交
2992
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
2993

A
Annie_wang 已提交
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let ss= fs.createStreamSync(filePath, "r+");
  ss.closeSync();
  ```

### flush

flush(): Promise&lt;void&gt;

Flushes the stream. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Return value**

A
Annie_wang 已提交
3012 3013
  | Type                 | Description           |
  | ------------------- | ------------- |
A
Annie_wang 已提交
3014
  | Promise&lt;void&gt; | Promise used to return the result.|
A
Annie_wang 已提交
3015 3016 3017

**Error codes**

A
Annie_wang 已提交
3018
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let ss= fs.createStreamSync(filePath, "r+");
  ss.flush().then(() => {
      console.info("Stream flushed");
  }).catch((err) => {
      console.info("flush failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

### flush

flush(callback: AsyncCallback&lt;void&gt;): void

Flushes the stream. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
3042 3043 3044
  | Name     | Type                       | Mandatory  | Description            |
  | -------- | ------------------------- | ---- | -------------- |
  | callback | AsyncCallback&lt;void&gt; | Yes   | Callback invoked when the stream is asynchronously flushed.|
A
Annie_wang 已提交
3045 3046 3047

**Error codes**

A
Annie_wang 已提交
3048
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let ss= fs.createStreamSync(filePath, "r+");
  ss.flush((err) => {
    if (err) {
      console.info("flush stream failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("flush success");
    }
  });
  ```

### flushSync

flushSync(): void

Synchronously flushes the stream.

**System capability**: SystemCapability.FileManagement.File.FileIO

A
Annie_wang 已提交
3072 3073
**Error codes**

A
Annie_wang 已提交
3074
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3075

A
Annie_wang 已提交
3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let ss= fs.createStreamSync(filePath, "r+");
  ss.flushSync();
  ```

### write

write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): Promise&lt;number&gt;

Writes data into the stream. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
3094 3095 3096
  | Name    | Type                             | Mandatory  | Description                                      |
  | ------- | ------------------------------- | ---- | ---------------------------------------- |
  | buffer  | ArrayBuffer\|string | Yes   | Data to write. It can be a string or data from a buffer.                    |
A
Annie_wang 已提交
3097
  | options | Object                          | No   | The options are as follows:<br>- **length** (number): length of the data to write. The default value is the buffer length.<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.|
A
Annie_wang 已提交
3098 3099 3100

**Return value**

A
Annie_wang 已提交
3101 3102 3103
  | Type                   | Description      |
  | --------------------- | -------- |
  | Promise&lt;number&gt; | Promise used to return the length of the data written.|
A
Annie_wang 已提交
3104 3105 3106

**Error codes**

A
Annie_wang 已提交
3107
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let ss= fs.createStreamSync(filePath, "r+");
  ss.write("hello, world",{ offset: 5, length: 5, encoding: 'utf-8' }).then((number) => {
      console.info("write succeed and size is:" + number);
  }).catch((err) => {
      console.info("write failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

### write

write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback&lt;number&gt;): void

Writes data into the stream. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
3131 3132 3133
  | Name  | Type                           | Mandatory| Description                                                        |
  | -------- | ------------------------------- | ---- | ------------------------------------------------------------ |
  | buffer   | ArrayBuffer\|string | Yes  | Data to write. It can be a string or data from a buffer.                    |
A
Annie_wang 已提交
3134
  | options  | Object                          | No  | The options are as follows:<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.|
A
Annie_wang 已提交
3135
  | callback | AsyncCallback&lt;number&gt;     | Yes  | Callback invoked when the data is written asynchronously.                              |
A
Annie_wang 已提交
3136 3137 3138

**Error codes**

A
Annie_wang 已提交
3139
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let ss= fs.createStreamSync(filePath, "r+");
  ss.write("hello, world", { offset: 5, length: 5, encoding :'utf-8'}, (err, bytesWritten) => {
    if (err) {
      console.info("write stream failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      if (bytesWritten) {
        console.info("write succeed and size is:" + bytesWritten);
      }
    }
  });
  ```

### writeSync

writeSync(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): number

Synchronously writes data into the stream.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
3167 3168 3169
  | Name    | Type                             | Mandatory  | Description                                      |
  | ------- | ------------------------------- | ---- | ---------------------------------------- |
  | buffer  | ArrayBuffer\|string | Yes   | Data to write. It can be a string or data from a buffer.                    |
A
Annie_wang 已提交
3170
  | options | Object                          | No   | The options are as follows:<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.|
A
Annie_wang 已提交
3171 3172 3173

**Return value**

A
Annie_wang 已提交
3174 3175 3176
  | Type    | Description      |
  | ------ | -------- |
  | number | Length of the data written in the file.|
A
Annie_wang 已提交
3177 3178 3179

**Error codes**

A
Annie_wang 已提交
3180
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let ss= fs.createStreamSync(filePath,"r+");
  let num = ss.writeSync("hello, world", {offset: 5, length: 5, encoding :'utf-8'});
  ```

### read

read(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): Promise&lt;number&gt;

Reads data from the stream. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
3200 3201 3202
  | Name    | Type         | Mandatory  | Description                                      |
  | ------- | ----------- | ---- | ---------------------------------------- |
  | buffer  | ArrayBuffer | Yes   | Buffer used to store the file read.                             |
A
Annie_wang 已提交
3203
  | options | Object      | No   | The options are as follows:<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to read the data. This parameter is optional. By default, data is read from the current position.|
A
Annie_wang 已提交
3204 3205 3206

**Return value**

A
Annie_wang 已提交
3207 3208 3209
  | Type                                | Description    |
  | ---------------------------------- | ------ |
  | Promise&lt;number&gt; | Promise used to return the data read.|
A
Annie_wang 已提交
3210 3211 3212

**Error codes**

A
Annie_wang 已提交
3213
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3214 3215 3216 3217 3218 3219 3220 3221 3222

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let ss = fs.createStreamSync(filePath, "r+");
  let buf = new ArrayBuffer(4096);
  ss.read(buf, {offset: 5, length: 5}).then((readLen) => {
    console.info("Read data successfully");
A
Annie_wang 已提交
3223
    console.log(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen))));
A
Annie_wang 已提交
3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238
  }).catch((err) => {
      console.info("read data failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

### read

read(buffer: ArrayBuffer, options?: { position?: number; offset?: number; length?: number; }, callback: AsyncCallback&lt;number&gt;): void

Reads data from the stream. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
3239 3240 3241
  | Name     | Type                                      | Mandatory  | Description                                      |
  | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
  | buffer   | ArrayBuffer                              | Yes   | Buffer used to store the file read.                             |
A
Annie_wang 已提交
3242
  | options  | Object                                   | No   | The options are as follows:<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to read the data. This parameter is optional. By default, data is read from the current position.|
A
Annie_wang 已提交
3243
  | callback | AsyncCallback&lt;number&gt; | Yes   | Callback invoked when data is read asynchronously from the stream.                        |
A
Annie_wang 已提交
3244 3245 3246

**Error codes**

A
Annie_wang 已提交
3247
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let ss = fs.createStreamSync(filePath, "r+");
  let buf = new ArrayBuffer(4096)
  ss.read(buf, {offset: 5, length: 5}, (err, readLen) => {
    if (err) {
      console.info("read stream failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.info("Read data successfully");
A
Annie_wang 已提交
3260
      console.log(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen))));
A
Annie_wang 已提交
3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274
    }
  });
  ```

### readSync

readSync(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number

Synchronously reads data from the stream.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
3275 3276 3277
  | Name    | Type         | Mandatory  | Description                                      |
  | ------- | ----------- | ---- | ---------------------------------------- |
  | buffer  | ArrayBuffer | Yes   | Buffer used to store the file read.                             |
A
Annie_wang 已提交
3278
  | options | Object      | No   | The options are as follows:<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to read the data. This parameter is optional. By default, data is read from the current position.<br>|
A
Annie_wang 已提交
3279 3280 3281

**Return value**

A
Annie_wang 已提交
3282 3283 3284
  | Type    | Description      |
  | ------ | -------- |
  | number | Length of the data read.|
A
Annie_wang 已提交
3285 3286 3287

**Error codes**

A
Annie_wang 已提交
3288
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let ss = fs.createStreamSync(filePath, "r+");
  let num = ss.readSync(new ArrayBuffer(4096), {offset: 5, length: 5});
  ```

## File

Represents a **File** object opened by **open()**.

**System capability**: SystemCapability.FileManagement.File.FileIO

### Attributes

| Name  | Type  | Readable  | Writable  | Description     |
| ---- | ------ | ---- | ---- | ------- |
| fd | number | Yes   | No   | FD of the file.|
A
Annie_wang 已提交
3309 3310
| path<sup>10+</sup> | string | Yes   | No   | Path of the file.|
| name<sup>10+</sup> | string | Yes   | No   | Name of the file.|
A
Annie_wang 已提交
3311

A
Annie_wang 已提交
3312 3313
### lock

A
Annie_wang 已提交
3314
lock(exclusive?: boolean): Promise\<void>
A
Annie_wang 已提交
3315 3316 3317 3318 3319 3320 3321

Applies an exclusive lock or a shared lock on this file in blocking mode. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
3322 3323 3324
  | Name    | Type         | Mandatory  | Description                                      |
  | ------- | ----------- | ---- | ---------------------------------------- |
  | exclusive  | boolean | No  | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock.      |
A
Annie_wang 已提交
3325 3326 3327

**Return value**

A
Annie_wang 已提交
3328 3329 3330
  | Type                                | Description    |
  | ---------------------------------- | ------ |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
3331 3332 3333

**Error codes**

A
Annie_wang 已提交
3334
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3335 3336 3337 3338

**Example**

  ```js
A
Annie_wang 已提交
3339
  let file = fs.openSync(pathDir + "/test.txt", fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
A
Annie_wang 已提交
3340 3341 3342 3343 3344 3345 3346 3347 3348
  file.lock(true).then(() => {
    console.log("lock file successful");
  }).catch((err) => {
      console.info("lock file failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

### lock

A
Annie_wang 已提交
3349
lock(exclusive?: boolean, callback: AsyncCallback\<void>): void
A
Annie_wang 已提交
3350 3351 3352 3353 3354 3355 3356

Applies an exclusive lock or a shared lock on this file in blocking mode. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
3357 3358 3359 3360
  | Name    | Type         | Mandatory  | Description                                      |
  | ------- | ----------- | ---- | ---------------------------------------- |
  | exclusive  | boolean | No  | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock.      |
  | callback | AsyncCallback&lt;void&gt; | Yes   | Callback invoked when the file is locked.  |     
A
Annie_wang 已提交
3361 3362 3363

**Error codes**

A
Annie_wang 已提交
3364
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3365 3366 3367 3368

**Example**

  ```js
A
Annie_wang 已提交
3369
  let file = fs.openSync(pathDir + "/test.txt", fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
A
Annie_wang 已提交
3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380
  file.lock(true, (err) => {
    if (err) {
      console.info("lock file failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      console.log("lock file successful");
    }
  });
  ```

### tryLock

A
Annie_wang 已提交
3381
tryLock(exclusive?: boolean): void
A
Annie_wang 已提交
3382 3383 3384 3385 3386 3387 3388

Applies an exclusive lock or a shared lock on this file in non-blocking mode.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

A
Annie_wang 已提交
3389 3390 3391
  | Name    | Type         | Mandatory  | Description                                      |
  | ------- | ----------- | ---- | ---------------------------------------- |
  | exclusive  | boolean | No  | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock.      |    
A
Annie_wang 已提交
3392 3393 3394

**Error codes**

A
Annie_wang 已提交
3395
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3396 3397 3398 3399

**Example**

  ```js
A
Annie_wang 已提交
3400
  let file = fs.openSync(pathDir + "/test.txt", fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
A
Annie_wang 已提交
3401 3402 3403 3404 3405 3406
  file.tryLock(true);
  console.log("lock file successful");
  ```

### unlock

A
Annie_wang 已提交
3407
unlock(): void
A
Annie_wang 已提交
3408 3409 3410 3411 3412

Unlocks this file synchronously.

**System capability**: SystemCapability.FileManagement.File.FileIO

A
Annie_wang 已提交
3413 3414
**Error codes**

A
Annie_wang 已提交
3415
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3416

A
Annie_wang 已提交
3417 3418 3419
**Example**

  ```js
A
Annie_wang 已提交
3420
  let file = fs.openSync(pathDir + "/test.txt", fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
A
Annie_wang 已提交
3421 3422 3423 3424 3425
  file.tryLock(true);
  file.unlock();
  console.log("unlock file successful");
  ```

A
Annie_wang 已提交
3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457

## RandomAccessFile

Randomly reads and writes a stream. Before invoking any API of **RandomAccessFile**, you need to use **createRandomAccess()** to create a **RandomAccessFile** instance synchronously or asynchronously.

**System capability**: SystemCapability.FileManagement.File.FileIO

### Attributes

| Name        | Type  | Readable | Writable | Description             |
| ----------- | ------ | ----  | ----- | ---------------- |
| fd          | number | Yes   | No   | FD of the file.|
| filePointer | number | Yes   | Yes   | Offset pointer to the **RandomAccessFile** instance.|

### setFilePointer<sup>10+</sup>

setFilePointer(): void

Sets the file offset pointer.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Error codes**

For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  randomAccessFile.setFilePointer(1);
A
Annie_wang 已提交
3458
  randomAccessFile.close();
A
Annie_wang 已提交
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478
  ```


### close<sup>10+</sup>

close(): void

Closes this **RandomAccessFile** instance synchronously.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Error codes**

For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
A
Annie_wang 已提交
3479
  randomAccessFile.close();
A
Annie_wang 已提交
3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510
  ```

### write<sup>10+</sup>

write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): Promise&lt;number&gt;

Writes data into a file. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

  | Name    | Type                             | Mandatory  | Description                                      |
  | ------- | ------------------------------- | ---- | ---------------------------------------- |
  | buffer  | ArrayBuffer\|string | Yes   | Data to write. It can be a string or data from a buffer.                    |
  | options | Object                          | No   | The options are as follows:<br>- **length** (number): length of the data to write. The default value is the buffer length.<br>- **offset** (number): start position to write the data (it is determined by **filePointer** plus **offset**). This parameter is optional. By default, data is written from the **filePointer**.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.|

**Return value**

  | Type                   | Description      |
  | --------------------- | -------- |
  | Promise&lt;number&gt; | Promise used to return the length of the data written.|

**Error codes**

For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
A
Annie_wang 已提交
3511
  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
A
Annie_wang 已提交
3512 3513 3514 3515
  let randomaccessfile = fs.createRandomAccessFileSync(file);
  let bufferLength = 4096;
  randomaccessfile.write(new ArrayBuffer(bufferLength), { offset: 1, length: 5 }).then((bytesWritten) => {
      console.info("randomAccessFile bytesWritten: " + bytesWritten);
A
Annie_wang 已提交
3516 3517
      randomaccessfile.close();
      fs.closeSync(file);
A
Annie_wang 已提交
3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547
  }).catch((err) => {
      console.info("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code);
  });

  ```

### write<sup>10+</sup>

write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback&lt;number&gt;): void

Writes data into a file. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

  | Name  | Type                           | Mandatory| Description                                                        |
  | -------- | ------------------------------- | ---- | ------------------------------------------------------------ |
  | buffer   | ArrayBuffer\|string | Yes  | Data to write. It can be a string or data from a buffer.                    |
  | options  | Object                          | No  | The options are as follows:<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to write the data (it is determined by **filePointer** plus **offset**). This parameter is optional. By default, data is written from the **filePointer**.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.|
  | callback | AsyncCallback&lt;number&gt;     | Yes  | Callback invoked when the data is written asynchronously.                              |

**Error codes**

For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
A
Annie_wang 已提交
3548
  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
A
Annie_wang 已提交
3549 3550 3551 3552 3553 3554 3555 3556
  let randomAccessFile = fs.createRandomAccessFileSync(file);
  let bufferLength = 4096;
  randomAccessFile.write(new ArrayBuffer(bufferLength), { offset: 1 }, function(err, bytesWritten) {
      if (err) {
          console.info("write failed with error message: " + err.message + ", error code: " + err.code);
      } else {
          if (bytesWritten) {
              console.info("write succeed and size is:" + bytesWritten);
A
Annie_wang 已提交
3557 3558
              randomAccessFile.close();
              fs.closeSync(file);
A
Annie_wang 已提交
3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592
          }
      }
  });
  ```

### writeSync<sup>10+</sup>

writeSync(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): number

Synchronously writes data into a file.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

  | Name    | Type                             | Mandatory  | Description                                      |
  | ------- | ------------------------------- | ---- | ---------------------------------------- |
  | buffer  | ArrayBuffer\|string | Yes   | Data to write. It can be a string or data from a buffer.                    |
  | options | Object                          | No   | The options are as follows:<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to write the data (it is determined by **filePointer** plus **offset**). This parameter is optional. By default, data is written from the **filePointer**.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.|

**Return value**

  | Type    | Description      |
  | ------ | -------- |
  | number | Length of the data written in the file.|

**Error codes**

For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
A
Annie_wang 已提交
3593
  let randomaccessfile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
A
Annie_wang 已提交
3594
  let bytesWritten = randomaccessfile.writeSync("hello, world", {offset: 5, length: 5, encoding :'utf-8'});
A
Annie_wang 已提交
3595 3596
  randomaccessfile.close();
  fs.closeSync(file);
A
Annie_wang 已提交
3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632
  ```

### read<sup>10+</sup>

read(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): Promise&lt;number&gt;

Reads data from a file. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

  | Name    | Type         | Mandatory  | Description                                      |
  | ------- | ----------- | ---- | ---------------------------------------- |
  | buffer  | ArrayBuffer | Yes   | Buffer used to store the file read.                             |
  | options | Object      | No   | The options are as follows:<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to read the data (it is determined by **filePointer** plus **offset**). This parameter is optional. By default, data is read from the **filePointer**.|

**Return value**

  | Type                                | Description    |
  | ---------------------------------- | ------ |
  | Promise&lt;number&gt; | Promise used to return the data read.|

**Error codes**

For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
  let randomaccessfile = fs.createRandomAccessFileSync(file);
  let bufferLength = 4096;
  randomaccessfile.read(new ArrayBuffer(bufferLength), { offset: 1, length: 5 }).then((readLength) => {
      console.info("randomAccessFile readLength: " + readLength);
A
Annie_wang 已提交
3633 3634
      randomaccessfile.close();
      fs.closeSync(file);
A
Annie_wang 已提交
3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664
  }).catch((err) => {
      console.info("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code);
  });
  ```

### read<sup>10+</sup>

read(buffer: ArrayBuffer, options?: { position?: number; offset?: number; length?: number; }, callback: AsyncCallback&lt;number&gt;): void

Reads data from a file. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

  | Name     | Type                                      | Mandatory  | Description                                      |
  | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
  | buffer   | ArrayBuffer                              | Yes   | Buffer used to store the file read.                             |
  | options  | Object                                   | No   | The options are as follows:<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to read the data (it is determined by **filePointer** plus **offset**). This parameter is optional. By default, data is read from the **filePointer**.|
  | callback | AsyncCallback&lt;number&gt; | Yes   | Callback invoked when data is read asynchronously from the stream.                        |

**Error codes**

For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
A
Annie_wang 已提交
3665
  let randomaccessfile = fs.createRandomAccessFileSync(file);
A
Annie_wang 已提交
3666 3667 3668 3669 3670 3671 3672
  let length = 20;
  randomaccessfile.read(new ArrayBuffer(length), { offset: 1, length: 5 }, function (err, readLength) {
    if (err) {
      console.info("read failed with error message: " + err.message + ", error code: " + err.code);
    } else {
      if (readLength) {
        console.info("read succeed and size is:" + readLength);
A
Annie_wang 已提交
3673 3674
        randomaccessfile.close();
        fs.closeSync(file);
A
Annie_wang 已提交
3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692
      }
    }
  });
  ```

### readSync<sup>10+</sup>

readSync(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number

Synchronously reads data from a file.

**System capability**: SystemCapability.FileManagement.File.FileIO

**Parameters**

  | Name    | Type         | Mandatory  | Description                                      |
  | ------- | ----------- | ---- | ---------------------------------------- |
  | buffer  | ArrayBuffer | Yes   | Buffer used to store the file read.                             |
A
Annie_wang 已提交
3693
  | options | Object      | No   | The options are as follows:<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to read the data (it is determined by **filePointer** plus **offset**). This parameter is optional. By default, data is read from the **filePointer**.<br>|
A
Annie_wang 已提交
3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708

**Return value**

  | Type    | Description      |
  | ------ | -------- |
  | number | Length of the data read.|

**Error codes**

For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
A
Annie_wang 已提交
3709
  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
A
Annie_wang 已提交
3710 3711 3712
  let randomaccessfile = fs.createRandomAccessFileSync(file);
  let length = 4096;
  let readLength = randomaccessfile.readSync(new ArrayBuffer(length));
A
Annie_wang 已提交
3713 3714
  randomaccessfile.close();
  fs.closeSync(file);
A
Annie_wang 已提交
3715 3716 3717
  ```


A
Annie_wang 已提交
3718 3719
## Watcher<sup>10+</sup>

A
Annie_wang 已提交
3720
Provides APIs for observing the changes of files or folders. Before using the APIs of **Watcher** , call **createWatcher()** to create a **Watcher** object.
A
Annie_wang 已提交
3721 3722 3723 3724 3725

### start<sup>10+</sup>

start(): void

A
Annie_wang 已提交
3726
Starts listening.
A
Annie_wang 已提交
3727 3728 3729 3730 3731

**System API**: This is a system API.

**System capability**: SystemCapability.FileManagement.File.FileIO

A
Annie_wang 已提交
3732 3733
**Error codes**

A
Annie_wang 已提交
3734
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3735

A
Annie_wang 已提交
3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748
**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let watcher = fs.createWatcher(filePath, 0xfff, () => {});
  watcher.start();
  watcher.stop();
  ```

### stop<sup>10+</sup>

stop(): void

A
Annie_wang 已提交
3749
Stops listening.
A
Annie_wang 已提交
3750 3751 3752 3753 3754

**System API**: This is a system API.

**System capability**: SystemCapability.FileManagement.File.FileIO

A
Annie_wang 已提交
3755 3756
**Error codes**

A
Annie_wang 已提交
3757
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
A
Annie_wang 已提交
3758

A
Annie_wang 已提交
3759 3760 3761 3762 3763 3764 3765 3766 3767
**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let watcher = fs.createWatcher(filePath, 0xfff, () => {});
  watcher.start();
  watcher.stop();
  ```

A
Annie_wang 已提交
3768 3769
## OpenMode

A
Annie_wang 已提交
3770
Defines the constants of the **mode** parameter used in **open()**. It specifies the mode for opening a file.
A
Annie_wang 已提交
3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785

**System capability**: SystemCapability.FileManagement.File.FileIO

| Name  | Type  | Value | Description     |
| ---- | ------ |---- | ------- |
| READ_ONLY | number |  0o0   | Open the file in read-only mode.|
| WRITE_ONLY | number | 0o1    | Open the file in write-only mode.|
| READ_WRITE | number | 0o2    | Open the file in read/write mode.|
| CREATE | number | 0o100    | Create a file if the specified file does not exist.|
| TRUNC | number | 0o1000    | If the file exists and is open in write-only or read/write mode, truncate the file length to 0.|
| APPEND | number | 0o2000   | Open the file in append mode. New data will be written to the end of the file.|
| NONBLOCK | number | 0o4000    | If **path** points to a named pipe (FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.|
| DIR | number | 0o200000    | If **path** does not point to a directory, throw an exception.|
| NOFOLLOW | number | 0o400000    | If **path** points to a symbolic link, throw an exception.|
| SYNC | number | 0o4010000    | Open the file in synchronous I/O mode.|
A
Annie_wang 已提交
3786

A
Annie_wang 已提交
3787
## Filter<sup>10+</sup>
A
Annie_wang 已提交
3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800

**System capability**: SystemCapability.FileManagement.File.FileIO

Defines the file filtering configuration, which can be used by **listFile()**.

| Name       | Type      | Description               |
| ----------- | --------------- | ------------------ |
| suffix | Array&lt;string&gt;     | Locate files that fully match the specified file name extensions, which are of the OR relationship.          |
| displayName    | Array&lt;string&gt;     | Locate files that fuzzy match the specified file names, which are of the OR relationship.|
| mimeType    | Array&lt;string&gt; | Locate files that fully match the specified MIME types, which are of the OR relationship.      |
| fileSizeOver    | number | Locate files that are greater than or equal to the specified size.      |
| lastModifiedAfter    | number | Locate files whose last modification time is the same or later than the specified time.      |
| excludeMedia    | boolean | Whether to exclude the files already in **Media**.      |
A
Annie_wang 已提交
3801

A
Annie_wang 已提交
3802
## ConflictFiles<sup>10+</sup>
A
Annie_wang 已提交
3803 3804 3805 3806 3807 3808 3809 3810 3811

**System capability**: SystemCapability.FileManagement.File.FileIO

Defines information about the conflicting files. It is used the **copyDir()** and **moveDir()**.

| Name       | Type      | Description               |
| ----------- | --------------- | ------------------ |
| srcFile | string     | Path of the source file.          |
| destFile    | string     | Path of the destination file.|