js-apis-file-fs.md 111.9 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**<br>
> 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 已提交
7 8 9 10 11 12 13

## Modules to Import

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

A
Annie_wang 已提交
14 15 16 17
## Error Code Description

The APIs of this module supports processing of error codes. For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).

A
Annie_wang 已提交
18 19
## Guidelines

A
Annie_wang 已提交
20
Before using the APIs provided by this module to perform operations on a file or folder, obtain the application sandbox path of the file or folder as follows:
A
Annie_wang 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

**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;
    }
}
 ```

**FA Model**

 ```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&lt;Stat&gt;

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 已提交
60
| file   | string\|number | Yes  | Application sandbox path or file descriptor (FD) of the file.|
A
Annie_wang 已提交
61 62 63

**Return value**

A
Annie_wang 已提交
64 65 66
  | Type                          | Description        |
  | ---------------------------- | ---------- |
  | Promise&lt;[Stat](#stat)&gt; | Promise used to return the file information obtained.|
A
Annie_wang 已提交
67 68 69 70

**Example**

  ```js
A
Annie_wang 已提交
71
  let filePath = pathDir + "/test.txt";
A
Annie_wang 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
  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&lt;Stat&gt;): 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 已提交
91
| file     | string\|number                            | Yes  | Application sandbox path or FD of the file.    |
A
Annie_wang 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| callback | AsyncCallback&lt;[Stat](#stat)&gt; | Yes  | Callback invoked to return the file information obtained.|

**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 已提交
118
| file   | string\|number | Yes  | Application sandbox path or FD of the file.|
A
Annie_wang 已提交
119 120 121 122


**Return value**

A
Annie_wang 已提交
123 124 125
  | Type           | Description        |
  | ------------- | ---------- |
  | [Stat](#stat) | File information obtained.|
A
Annie_wang 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

**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&lt;boolean&gt;

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 已提交
146
| path   | string | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
147 148 149

**Return value**

A
Annie_wang 已提交
150 151
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
A
Annie_wang 已提交
152
  | Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means the file exists; the value **false** means the opposite.|
A
Annie_wang 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

**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&lt;boolean&gt;): 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 已提交
180
| path     | string                    | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
| callback | AsyncCallback&lt;boolean&gt; | Yes  | Callback invoked to return the result.                |

**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 已提交
210 211 212 213 214 215 216
| path   | string | Yes  | Application sandbox path of the file.                                  |

**Return value**

  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | boolean | Returns **true** if the file exists; returns **false** otherwise.|
A
Annie_wang 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

**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

close(file: File|number): Promise&lt;void&gt;

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

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

**Parameters**

A
Annie_wang 已提交
243 244 245
  | Name | Type    | Mandatory  | Description          |
  | ---- | ------ | ---- | ------------ |
  | file   | [File](#file)\|number | Yes   | File object or FD of the file to close.|
A
Annie_wang 已提交
246 247 248

**Return value**

A
Annie_wang 已提交
249 250 251
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

**Example**

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

## fs.close

close(file: File|number, callback: AsyncCallback&lt;void&gt;): void

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

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

**Parameters**

A
Annie_wang 已提交
276 277 278 279
  | Name     | Type                       | Mandatory  | Description          |
  | -------- | ------------------------- | ---- | ------------ |
  | file       | [File](#file)\|number                  | Yes   | File object or FD of the file to close.|
  | callback | AsyncCallback&lt;void&gt; | Yes   | Callback invoked when the file is closed asynchronously.|
A
Annie_wang 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304

**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");
    }
  });
  ```

## fs.closeSync

closeSync(file: File|number): void

Synchronously closes a file.

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

**Parameters**

A
Annie_wang 已提交
305 306 307
  | Name | Type    | Mandatory  | Description          |
  | ---- | ------ | ---- | ------------ |
  | file   | [File](#file)\|number | Yes   | File object or FD of the file to close.|
A
Annie_wang 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326

**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&lt;void&gt;

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

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

**Parameters**

A
Annie_wang 已提交
327 328 329 330 331
  | 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 of the same name in the destination path. The default value is **0**, which is the only value supported.<br>**0**: overwrite the file of the same name.|
A
Annie_wang 已提交
332 333 334

**Return value**

A
Annie_wang 已提交
335 336 337
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
338 339 340 341

**Example**

  ```js
A
Annie_wang 已提交
342 343
  let srcPath = pathDir + "/srcDir/test.txt";
  let dstPath = pathDir + "/dstDir/test.txt";
A
Annie_wang 已提交
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
  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 已提交
361 362 363 364 365 366
  | 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 of the same name in the destination path. 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 when the file is copied asynchronously.                            |
A
Annie_wang 已提交
367 368 369 370

**Example**

  ```js
A
Annie_wang 已提交
371 372
  let srcPath = pathDir + "/srcDir/test.txt";
  let dstPath = pathDir + "/dstDir/test.txt";
A
Annie_wang 已提交
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
  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 已提交
393 394 395 396 397
  | 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 of the same name in the destination path. 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 已提交
398 399 400 401

**Example**

  ```js
A
Annie_wang 已提交
402 403
  let srcPath = pathDir + "/srcDir/test.txt";
  let dstPath = pathDir + "/dstDir/test.txt";
A
Annie_wang 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
  fs.copyFileSync(srcPath, dstPath);
  ```


## 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 已提交
420
| path   | string | Yes  | Application sandbox path of the directory.                                  |
A
Annie_wang 已提交
421 422 423

**Return value**

A
Annie_wang 已提交
424 425 426
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
427 428 429 430

**Example**

  ```js
A
Annie_wang 已提交
431
  let dirPath = pathDir + "/testDir";
A
Annie_wang 已提交
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
  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 已提交
452
| path     | string                    | Yes  | Application sandbox path of the directory.                                  |
A
Annie_wang 已提交
453 454 455 456 457
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked when the directory is created asynchronously.                            |

**Example**

  ```js
A
Annie_wang 已提交
458
  let dirPath = pathDir + "/testDir";
A
Annie_wang 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
  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 已提交
481
| path   | string | Yes  | Application sandbox path of the directory.                                  |
A
Annie_wang 已提交
482 483 484 485

**Example**

  ```js
A
Annie_wang 已提交
486
  let dirPath = pathDir + "/testDir";
A
Annie_wang 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
  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 已提交
503
| path   | string | Yes  | Application sandbox path or URI of the file.                                  |
A
Annie_wang 已提交
504 505 506 507
| 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 open 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.|

**Return value**

A
Annie_wang 已提交
508 509 510
  | Type                   | Description         |
  | --------------------- | ----------- |
  | Promise&lt;[File](#file)&gt; | Promise used to return the file object.|
A
Annie_wang 已提交
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535

**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 已提交
536
| path     | string                          | Yes  | Application sandbox path or URI of the file.                                  |
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
| 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 open 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.|

**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 已提交
564
| path   | string | Yes  | Application sandbox path or URI of the file.                                  |
A
Annie_wang 已提交
565
| 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 open 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 已提交
566 567 568

**Return value**

A
Annie_wang 已提交
569 570 571
  | Type    | Description         |
  | ------ | ----------- |
  | [File](#file) | File object opened.|
A
Annie_wang 已提交
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599

**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.                          |
| options | Object      | No  | The options are as follows:<br>- **offset** (number): position of the data to read in the file. 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.|

**Return value**

A
Annie_wang 已提交
600 601 602
  | Type                                | Description    |
  | ---------------------------------- | ------ |
  | Promise&lt;number&gt; | Promise used to return the data read.|
A
Annie_wang 已提交
603 604 605 606 607 608 609 610 611

**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 已提交
612
      console.info(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen))));
A
Annie_wang 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
      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 已提交
629 630 631 632 633 634
  | Name     | Type                                      | Mandatory  | Description                                      |
  | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
  | fd       | number                                   | Yes   | FD of the file.                            |
  | buffer   | ArrayBuffer                              | Yes   | Buffer used to store the file data read.                       |
  | options | Object      | No  | The options are as follows:<br>- **offset** (number): position of the data to read in the file. 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.|
  | callback | AsyncCallback&lt;number&gt; | Yes   | Callback invoked when the data is read asynchronously.                            |
A
Annie_wang 已提交
635 636 637 638 639 640 641 642 643 644 645 646

**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 已提交
647
      console.info(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen))));
A
Annie_wang 已提交
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
      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 已提交
664 665 666 667 668
  | Name    | Type         | Mandatory  | Description                                      |
  | ------- | ----------- | ---- | ---------------------------------------- |
  | fd      | number      | Yes   | FD of the file.                            |
  | buffer  | ArrayBuffer | Yes   | Buffer used to store the file data read.                       |
  | options | Object      | No  | The options are as follows:<br>- **offset** (number): position of the data to read in the file. 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 已提交
669 670 671

**Return value**

A
Annie_wang 已提交
672 673 674
  | Type    | Description      |
  | ------ | -------- |
  | number | Length of the data read.|
A
Annie_wang 已提交
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698

**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 已提交
699
| path   | string | Yes  | Application sandbox path of the directory.|
A
Annie_wang 已提交
700 701 702

**Return value**

A
Annie_wang 已提交
703 704 705
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
706 707 708 709

**Example**

  ```js
A
Annie_wang 已提交
710
  let dirPath = pathDir + "/testDir";
A
Annie_wang 已提交
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
  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 已提交
731
| path     | string                    | Yes  | Application sandbox path of the directory.|
A
Annie_wang 已提交
732 733 734 735 736
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked when the directory is deleted asynchronously.  |

**Example**

  ```js
A
Annie_wang 已提交
737
  let dirPath = pathDir + "/testDir";
A
Annie_wang 已提交
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
  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 已提交
760
| path   | string | Yes  | Application sandbox path of the directory.|
A
Annie_wang 已提交
761 762 763 764

**Example**

  ```js
A
Annie_wang 已提交
765
  let dirPath = pathDir + "/testDir";
A
Annie_wang 已提交
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
  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 已提交
782
| path   | string | Yes  | Application sandbox path of the file.|
A
Annie_wang 已提交
783 784 785

**Return value**

A
Annie_wang 已提交
786 787 788
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813

**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 已提交
814
| path     | string                    | Yes  | Application sandbox path of the file.|
A
Annie_wang 已提交
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked when the file is deleted asynchronously.  |

**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 已提交
843
| path   | string | Yes  | Application sandbox path of the file.|
A
Annie_wang 已提交
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862

**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 已提交
863 864 865 866 867
  | 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.                    |
  | 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.|
A
Annie_wang 已提交
868 869 870

**Return value**

A
Annie_wang 已提交
871 872 873
  | Type                   | Description      |
  | --------------------- | -------- |
  | Promise&lt;number&gt; | Promise used to return the length of the data written.|
A
Annie_wang 已提交
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898

**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 已提交
899 900 901 902 903 904
  | 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.                    |
  | 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.|
  | callback | AsyncCallback&lt;number&gt;     | Yes   | Callback invoked when the data is written asynchronously.                      |
A
Annie_wang 已提交
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931

**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 已提交
932 933 934 935 936
  | 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.                    |
  | 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.|
A
Annie_wang 已提交
937 938 939

**Return value**

A
Annie_wang 已提交
940 941 942
  | Type    | Description      |
  | ------ | -------- |
  | number | Length of the data written in the file.|
A
Annie_wang 已提交
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965

**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 已提交
966 967
| 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 已提交
968 969 970

**Return value**

A
Annie_wang 已提交
971 972 973
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999

**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 已提交
1000 1001
| 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 已提交
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback that returns no value.  |

**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 已提交
1031 1032
| 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 已提交
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054

**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 已提交
1055
| filePath | string | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
1056 1057 1058 1059
| options  | Object | No  | The options are as follows:<br>- **offset** (number): position of the data to read in the file. 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 string to be encoded. The default value is **'utf-8'**, which is the only value supported.|

**Return value**

A
Annie_wang 已提交
1060 1061 1062
  | Type                   | Description        |
  | --------------------- | ---------- |
  | Promise&lt;string&gt; | Promise used to return the content read.|
A
Annie_wang 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087

**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 已提交
1088
| filePath | string                      | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
1089
| options  | Object                      | No  | The options are as follows:<br>- **offset** (number): position of the data to read in the file. 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 string to be encoded. The default value is **'utf-8'**, which is the only value supported.|
A
Annie_wang 已提交
1090
| callback | AsyncCallback&lt;string&gt; | Yes  | Callback invoked to return the content read.                        |
A
Annie_wang 已提交
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117

**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 已提交
1118
| filePath | string | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
1119 1120 1121 1122
| options  | Object | No  | The options are as follows:<br>- **offset** (number): position of the data to read in the file. 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 string to be encoded. The default value is **'utf-8'**, which is the only value supported.|

**Return value**

A
Annie_wang 已提交
1123 1124 1125
  | Type  | Description                |
  | ------ | -------------------- |
  | string | Promise used to return the content of the file read.|
A
Annie_wang 已提交
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146

**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 已提交
1147
| path   | string | Yes  | Application sandbox path of the file.|
A
Annie_wang 已提交
1148 1149 1150

**Return value**

A
Annie_wang 已提交
1151 1152 1153
  | Type                          | Description        |
  | ---------------------------- | ---------- |
  | Promise&lt;[Stat](#stat)&gt; | Promise used to return the symbolic link information obtained. For details, see **stat**.|
A
Annie_wang 已提交
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178

**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 已提交
1179
| path     | string                             | Yes  | Application sandbox path of the file.|
A
Annie_wang 已提交
1180
| callback | AsyncCallback&lt;[Stat](#stat)&gt; | Yes  | Callback invoked to return the symbolic link information obtained.      |
A
Annie_wang 已提交
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206

**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 已提交
1207
| path   | string | Yes  | Application sandbox path of the file.|
A
Annie_wang 已提交
1208 1209 1210

**Return value**

A
Annie_wang 已提交
1211 1212 1213
  | Type           | Description        |
  | ------------- | ---------- |
  | [Stat](#stat) | File information obtained.|
A
Annie_wang 已提交
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225

**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 已提交
1226
Renames a file or folder. This API uses a promise to return the result.
A
Annie_wang 已提交
1227 1228 1229 1230 1231 1232 1233

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

**Parameters**

| Name | Type  | Mandatory| Description                        |
| ------- | ------ | ---- | ---------------------------- |
A
Annie_wang 已提交
1234 1235
| oldPath | string | Yes  | Application sandbox path of the file to rename.|
| newPath | string | Yes  | Application sandbox path of the renamed file.  |
A
Annie_wang 已提交
1236 1237 1238

**Return value**

A
Annie_wang 已提交
1239 1240 1241
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
1242 1243 1244 1245 1246

**Example**

  ```js
  let srcFile = pathDir + "/test.txt";
A
Annie_wang 已提交
1247
  let dstFile = pathDir + "/new.txt";
A
Annie_wang 已提交
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
  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 已提交
1259
Renames a file or folder. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
1260 1261 1262 1263 1264 1265 1266

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

**Parameters**

| Name  | Type                     | Mandatory| Description                        |
| -------- | ------------------------- | ---- | ---------------------------- |
A
Annie_wang 已提交
1267 1268
| oldPath | string | Yes  | Application sandbox path of the file to rename.|
| newPath | string | Yes  | Application sandbox path of the renamed file.  |
A
Annie_wang 已提交
1269 1270 1271 1272 1273 1274
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked when the file is asynchronously renamed.  |

**Example**

  ```js
  let srcFile = pathDir + "/test.txt";
A
Annie_wang 已提交
1275
  let dstFile = pathDir + "/new.txt";
A
Annie_wang 已提交
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
  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 已提交
1289
Renames a file or folder synchronously.
A
Annie_wang 已提交
1290 1291 1292 1293 1294 1295 1296

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

**Parameters**

| Name | Type  | Mandatory| Description                        |
| ------- | ------ | ---- | ---------------------------- |
A
Annie_wang 已提交
1297 1298
| oldPath | string | Yes  | Application sandbox path of the file to rename.|
| newPath | string | Yes  | Application sandbox path of the renamed file.  |
A
Annie_wang 已提交
1299 1300 1301 1302 1303

**Example**

  ```js
  let srcFile = pathDir + "/test.txt";
A
Annie_wang 已提交
1304
  let dstFile = pathDir + "/new.txt";
A
Annie_wang 已提交
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
  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 已提交
1319 1320 1321
  | Name | Type    | Mandatory  | Description          |
  | ---- | ------ | ---- | ------------ |
  | fd   | number | Yes   | FD of the file.|
A
Annie_wang 已提交
1322 1323 1324

**Return value**

A
Annie_wang 已提交
1325 1326 1327
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351

**Example**

  ```js
  let filePath = pathDir + "/test.txt";
  let file = fs.openSync(filePath);
  fs.fsync(file.fd).then(() => {
      console.info("Data flushed");
  }).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 已提交
1352 1353 1354 1355
  | 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 已提交
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376

**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 已提交
1377
Flushes data of a file to disk synchronously.
A
Annie_wang 已提交
1378 1379 1380 1381 1382

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

**Parameters**

A
Annie_wang 已提交
1383 1384 1385
  | Name | Type    | Mandatory  | Description          |
  | ---- | ------ | ---- | ------------ |
  | fd   | number | Yes   | FD of the file.|
A
Annie_wang 已提交
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406

**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 已提交
1407 1408 1409
  | Name | Type    | Mandatory  | Description          |
  | ---- | ------ | ---- | ------------ |
  | fd   | number | Yes   | FD of the file.|
A
Annie_wang 已提交
1410 1411 1412

**Return value**

A
Annie_wang 已提交
1413 1414 1415
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440

**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 已提交
1441 1442 1443 1444
  | 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 已提交
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464

**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 已提交
1465
Synchronizes data in a file synchronously.
A
Annie_wang 已提交
1466 1467 1468 1469 1470

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

**Parameters**

A
Annie_wang 已提交
1471 1472 1473
  | Name | Type    | Mandatory  | Description          |
  | ---- | ------ | ---- | ------------ |
  | fd   | number | Yes   | FD of the file.|
A
Annie_wang 已提交
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496

**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 已提交
1497 1498
| target  | string | Yes  | Application sandbox path of the source file.    |
| srcPath | string | Yes  | Application sandbox path of the symbolic link.|
A
Annie_wang 已提交
1499 1500 1501

**Return value**

A
Annie_wang 已提交
1502 1503 1504
  | Type                 | Description                          |
  | ------------------- | ---------------------------- |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
1505 1506 1507 1508 1509

**Example**

  ```js
  let srcFile = pathDir + "/test.txt";
A
Annie_wang 已提交
1510
  let dstFile = pathDir + "/test";
A
Annie_wang 已提交
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
  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 已提交
1530 1531
| target   | string                    | Yes  | Application sandbox path of the source file.        |
| srcPath  | string                    | Yes  | Application sandbox path of the symbolic link.    |
A
Annie_wang 已提交
1532 1533 1534 1535 1536 1537
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked when the symbolic link is created asynchronously.|

**Example**

  ```js
  let srcFile = pathDir + "/test.txt";
A
Annie_wang 已提交
1538
  let dstFile = pathDir + "/test";
A
Annie_wang 已提交
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
  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 已提交
1560 1561
| target  | string | Yes  | Application sandbox path of the source file.    |
| srcPath | string | Yes  | Application sandbox path of the symbolic link.|
A
Annie_wang 已提交
1562 1563 1564 1565 1566

**Example**

  ```js
  let srcFile = pathDir + "/test.txt";
A
Annie_wang 已提交
1567
  let dstFile = pathDir + "/test";
A
Annie_wang 已提交
1568 1569 1570
  fs.symlinkSync(srcFile, dstFile);
  ```

A
Annie_wang 已提交
1571 1572 1573 1574 1575
## fs.listFile
listFile(path: string, options?: {
    recursion?: boolean;
    listNum?: number;
    filter?: Filter;
A
Annie_wang 已提交
1576
}): Promise<string[]>
A
Annie_wang 已提交
1577

A
Annie_wang 已提交
1578
Lists all files in a directory. This API uses a promise to return the result.<br>This API supports recursive listing of all files (including files in subdirectories) and file filtering.
A
Annie_wang 已提交
1579 1580 1581 1582 1583

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

**Parameters**

A
Annie_wang 已提交
1584 1585
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
A
Annie_wang 已提交
1586 1587
  | 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 已提交
1588 1589 1590

**options parameters**

A
Annie_wang 已提交
1591 1592
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
A
Annie_wang 已提交
1593
  | recursion | boolean | No   | Whether to list all files in subdirectories recursively. The default value is **false**.|
A
Annie_wang 已提交
1594 1595
  | 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 已提交
1596 1597 1598

**Return value**

A
Annie_wang 已提交
1599 1600 1601
  | Type                  | Description        |
  | --------------------- | ---------- |
  | Promise&lt;string[]&gt; | Promise used to return the files names listed.|
A
Annie_wang 已提交
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617

**Example**

  ```js
  let options = {
    "recursion": false,
    "listNum": 0,
    "filter": {
      "suffix": [".png", ".jpg", ".jpeg"],
      "displayName": ["%abc", "efg%"],
      "fileSizeOver": 1024,
      "lastModifiedAfter": new Date().getTime(),
    }
  };
  fs.listFile(pathDir, options).then((filenames) => {
    console.info("listFile succeed");
A
Annie_wang 已提交
1618
    for (let i = 0; i < filenames.length; i++) {
A
Annie_wang 已提交
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
      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 已提交
1631
}, callback: AsyncCallback<string[]>): void
A
Annie_wang 已提交
1632

A
Annie_wang 已提交
1633
Lists all files in a directory. This API uses an asynchronous callback to return the result.<br>This API supports recursive listing of all files (including files in subdirectories) and file filtering.
A
Annie_wang 已提交
1634 1635 1636

**Parameters**

A
Annie_wang 已提交
1637 1638
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
A
Annie_wang 已提交
1639 1640
  | 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 已提交
1641
  | callback | AsyncCallback&lt;string[]&gt; | Yes   | Callback invoked to return the file names listed.             |
A
Annie_wang 已提交
1642 1643 1644

**options parameters**

A
Annie_wang 已提交
1645 1646
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
A
Annie_wang 已提交
1647
  | recursion | boolean | No   | Whether to list all files in subdirectories recursively. The default value is **false**.|
A
Annie_wang 已提交
1648 1649
  | 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 已提交
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668

**Example**

  ```js
  let options = {
    "recursion": false,
    "listNum": 0,
    "filter": {
      "suffix": [".png", ".jpg", ".jpeg"],
      "displayName": ["%abc", "efg%"],
      "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 已提交
1669
      for (let i = 0; i < filenames.length; i++) {
A
Annie_wang 已提交
1670 1671 1672 1673 1674 1675
        console.info("filename: %s", filenames[i]);
      }
    }
  });
  ```

A
Annie_wang 已提交
1676
## fs.listFileSync
A
Annie_wang 已提交
1677 1678 1679 1680 1681

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

A
Annie_wang 已提交
1684
Lists all files in a directory synchronously. This API supports recursive listing of all files (including files in subdirectories) and file filtering.
A
Annie_wang 已提交
1685 1686 1687

**Parameters**

A
Annie_wang 已提交
1688 1689
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
A
Annie_wang 已提交
1690 1691
  | 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 已提交
1692 1693 1694

**options parameters**

A
Annie_wang 已提交
1695 1696
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
A
Annie_wang 已提交
1697
  | recursion | boolean | No   | Whether to list all files in subdirectories recursively. The default value is **false**.|
A
Annie_wang 已提交
1698 1699
  | 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 已提交
1700 1701 1702

**Return value**

A
Annie_wang 已提交
1703 1704 1705
  | Type                  | Description        |
  | --------------------- | ---------- |
  | string[] | File names listed.|
A
Annie_wang 已提交
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721

**Example**

  ```js
  let options = {
    "recursion": false,
    "listNum": 0,
    "filter": {
      "suffix": [".png", ".jpg", ".jpeg"],
      "displayName": ["%abc", "efg%"],
      "fileSizeOver": 1024,
      "lastModifiedAfter": new Date().getTime(),
    }
  };
  let filenames = fs.listFileSync(pathDir, options);
  console.info("listFile succeed");
A
Annie_wang 已提交
1722
  for (let i = 0; i < filenames.length; i++) {
A
Annie_wang 已提交
1723 1724 1725
    console.info("filename: %s", filenames[i]);
  }
  ```
A
Annie_wang 已提交
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805

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

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

Moves a folder. 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 source folder.|
  | dest | string | Yes   | Application sandbox path of the destination folder.|
  | mode | number | No   | Mode for moving the folder. The default value is **0**.<br>- **0**: Throw an exception if the destination directory has folders of the same names with the source folder.<br>- **1**: Throw an exception if the destination directory has files of the same names with the source folder. All files without conflicts in the source folder are moved to the destination folder, and all files without conflicts in the destination folder are retained. The **data** in the error thrown provides information about the conflict files.<br>- **2**: Forcibly overwrite the files with the same names in the destination folder. The files with the the same names in the destination folder are overwritten forcibly; the files without conflicts in the destination folder are retained.<br>- **3**: Forcibly overwrite the destination folder. Move the source folder to the destination directory and make the destination folder completely the same as the source folder. All the original files in the destination folder are not retained.|

**Return value**

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

**Example**

  ```js
  // move directory from srcPath to destPath/srcPath
  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>

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

Moves a folder. 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 source folder.|
  | dest | string | Yes   | Application sandbox path of the destination folder.|
  | mode | number | No   | Whether to overwrite the file of the same name in the destination directory. The default value is **0**.<br>- **0**: Throw an exception if the destination directory has folders of the same names with the source folder.<br>- **1**: Throw an exception if the destination directory has files of the same names with the source folder. All files without conflicts in the source folder are moved to the destination folder, and all files without conflicts in the destination folder are retained. The **data** in the error thrown provides information about the conflict files.<br>- **2**: Forcibly overwrite the files with the same names in the destination folder. The files with the the same names in the destination folder are overwritten forcibly; the files without conflicts in the destination folder are retained.<br>- **3**: Forcibly overwrite the destination folder. Move the source folder to the destination directory and make the destination folder completely the same as the source folder. All the original files in the destination folder are not retained.|
  | callback | AsyncCallback&lt;void&gt; | Yes   | Callback invoked when the folder is moved.             |

**Example**

  ```js
  // move directory from srcPath to destPath/srcPath
  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 已提交
1806
## fs.moveFile
A
Annie_wang 已提交
1807

A
Annie_wang 已提交
1808
moveFile(src: string, dest: string, mode?: number): Promise\<void>
A
Annie_wang 已提交
1809 1810 1811 1812 1813 1814 1815

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

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

**Parameters**

A
Annie_wang 已提交
1816 1817
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
A
Annie_wang 已提交
1818 1819
  | src | string | Yes   | Application sandbox path of the source file.|
  | dest | string | Yes   | Application sandbox path of the destination file.|
A
Annie_wang 已提交
1820
  | mode | number | No   | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.|
A
Annie_wang 已提交
1821

A
Annie_wang 已提交
1822 1823 1824 1825 1826 1827
**Return value**

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

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

  ```js
A
Annie_wang 已提交
1831 1832
  let srcPath = pathDir + "/source.txt";
  let destPath = pathDir + "/dest.txt";
A
Annie_wang 已提交
1833 1834 1835 1836 1837 1838 1839
  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 已提交
1840
## fs.moveFile
A
Annie_wang 已提交
1841

A
Annie_wang 已提交
1842
moveFile(src: string, dest: string, mode?: number, callback: AsyncCallback\<void>): void
A
Annie_wang 已提交
1843 1844 1845 1846 1847 1848 1849

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

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

**Parameters**

A
Annie_wang 已提交
1850 1851
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
A
Annie_wang 已提交
1852 1853
  | src | string | Yes   | Application sandbox path of the source file.|
  | dest | string | Yes   | Application sandbox path of the destination file.|
A
Annie_wang 已提交
1854 1855
  | mode | number | No   | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.|
  | callback | AsyncCallback&lt;void&gt; | Yes   | Callback invoked when the file is moved.             |
A
Annie_wang 已提交
1856 1857 1858 1859

**Example**

  ```js
A
Annie_wang 已提交
1860 1861
  let srcPath = pathDir + "/source.txt";
  let destPath = pathDir + "/dest.txt";
A
Annie_wang 已提交
1862 1863 1864 1865 1866 1867 1868 1869 1870
  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 已提交
1871
## fs.moveFileSync
A
Annie_wang 已提交
1872

A
Annie_wang 已提交
1873
moveFile(src: string, dest: string, mode?: number): void
A
Annie_wang 已提交
1874 1875 1876 1877 1878 1879 1880

Moves a file synchronously.

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

**Parameters**

A
Annie_wang 已提交
1881 1882
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
A
Annie_wang 已提交
1883 1884
  | src | string | Yes   | Application sandbox path of the source file.|
  | dest | string | Yes   | Application sandbox path of the destination file.|
A
Annie_wang 已提交
1885
  | mode | number | No   | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.|
A
Annie_wang 已提交
1886 1887 1888 1889

**Example**

  ```js
A
Annie_wang 已提交
1890 1891
  let srcPath = pathDir + "/source.txt";
  let destPath = pathDir + "/dest.txt";
A
Annie_wang 已提交
1892 1893 1894 1895
  fs.moveFileSync(srcPath, destPath, 0);
  console.info("move file succeed");
  ```

A
Annie_wang 已提交
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
## 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 已提交
1906 1907 1908
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | prefix | string | Yes   | A randomly generated string used to replace "XXXXXX" in a directory.|
A
Annie_wang 已提交
1909 1910 1911

**Return value**

A
Annie_wang 已提交
1912 1913 1914
  | Type                  | Description        |
  | --------------------- | ---------- |
  | Promise&lt;string&gt; | Promise used to return the unique directory generated.|
A
Annie_wang 已提交
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936

**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 已提交
1937 1938 1939 1940
  | 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 已提交
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963

**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 已提交
1964 1965 1966
  | Name   | Type    | Mandatory  | Description                         |
  | ------ | ------ | ---- | --------------------------- |
  | prefix | string | Yes   | A randomly generated string used to replace "XXXXXX" in a directory.|
A
Annie_wang 已提交
1967 1968 1969

**Return value**

A
Annie_wang 已提交
1970 1971 1972
  | Type   | Description        |
  | ------ | ---------- |
  | string | Unique path generated.|
A
Annie_wang 已提交
1973 1974 1975 1976 1977

**Example**

  ```js
  let res = fs.mkdtempSync(pathDir + "/XXXXXX");
A
Annie_wang 已提交
1978
  ```  
A
Annie_wang 已提交
1979 1980 1981 1982 1983

## fs.createStream

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

A
Annie_wang 已提交
1984
Creates a stream based on the file path. This API uses a promise to return the result.
A
Annie_wang 已提交
1985 1986 1987 1988 1989 1990 1991

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

**Parameters**

| Name| Type  | Mandatory| Description                                                        |
| ------ | ------ | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
1992
| path   | string | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
1993 1994 1995 1996
| 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 已提交
1997 1998 1999
  | Type                               | Description       |
  | --------------------------------- | --------- |
  | Promise&lt;[Stream](#stream)&gt; | Promise used to return the result.|
A
Annie_wang 已提交
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016

**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 已提交
2017
Creates a stream based on the file path. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
2018 2019 2020 2021 2022 2023 2024

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

**Parameters**

| Name  | Type                                   | Mandatory| Description                                                        |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
2025
| path     | string                                  | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
2026
| 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 已提交
2027
| callback | AsyncCallback&lt;[Stream](#stream)&gt; | Yes  | Callback invoked when the stream is created asynchronously.                                  |
A
Annie_wang 已提交
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045

**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 已提交
2046
Synchronously creates a stream based on the file path.
A
Annie_wang 已提交
2047 2048 2049 2050 2051 2052 2053

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

**Parameters**

| Name| Type  | Mandatory| Description                                                        |
| ------ | ------ | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
2054
| path   | string | Yes  | Application sandbox path of the file.                                  |
A
Annie_wang 已提交
2055 2056 2057 2058
| 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 已提交
2059 2060 2061
  | Type               | Description       |
  | ------------------ | --------- |
  | [Stream](#stream) | Stream opened.|
A
Annie_wang 已提交
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074

**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 已提交
2075
Opens a stream based on the file descriptor. This API uses a promise to return the result.
A
Annie_wang 已提交
2076 2077 2078 2079 2080

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

**Parameters**

A
Annie_wang 已提交
2081 2082 2083 2084
  | 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 已提交
2085 2086 2087

**Return value**

A
Annie_wang 已提交
2088 2089 2090
  | Type                              | Description       |
  | --------------------------------- | --------- |
  | Promise&lt;[Stream](#stream)&gt; | Promise used to return the result.|
A
Annie_wang 已提交
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109

**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 已提交
2110
Opens a stream based on the file descriptor. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
2111 2112 2113 2114 2115

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

**Parameters**

A
Annie_wang 已提交
2116 2117 2118 2119 2120
  | 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).|
  | callback | AsyncCallback&lt;[Stream](#stream)&gt; | Yes   | Callback invoked when the stream is open asynchronously.                           |
A
Annie_wang 已提交
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146

**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

Synchronously opens a stream based on the file descriptor.

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

**Parameters**

A
Annie_wang 已提交
2147 2148 2149 2150
  | 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 已提交
2151 2152 2153

**Return value**

A
Annie_wang 已提交
2154 2155 2156
  | Type               | Description       |
  | ------------------ | --------- |
  | [Stream](#stream) | Stream opened.|
A
Annie_wang 已提交
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166

**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 已提交
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
## 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 已提交
2179 2180
  | Name | Type    | Mandatory  | Description                                      |
  | ---- | ------ | ---- | ---------------------------------------- |
A
Annie_wang 已提交
2181 2182
  | path   | string | Yes   | Application sandbox path of the file or directory to observe.                            |
  | 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 changed.<br>- **0x8: IN_CLOSE_WRITE**: The file opened for writing is closed.<br>- **0x10: IN_CLOSE_NOWRITE**: The file or directory not opened for writing is closed.<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 已提交
2183
  | listener   | WatchEventListener | Yes   | Callback invoked when an observed event occurs. The callback will be invoked each time an observed event occurs.                            |
A
Annie_wang 已提交
2184 2185 2186

**Return value**

A
Annie_wang 已提交
2187 2188 2189
  | Type               | Description       |
  | ------------------ | --------- |
  | [Watcher](#watcher10) | **Watcher** object created.|
A
Annie_wang 已提交
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220

**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 已提交
2221 2222 2223 2224
  | Name | Type    | Mandatory  | Description                                      |
  | ---- | ------ | ---- | ---------------------------------------- |
  | event   | WatchEvent | Yes   | Event for the callback to invoke.                            |
 
A
Annie_wang 已提交
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
## 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 已提交
2239 2240 2241 2242 2243 2244 2245 2246 2247
## 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 已提交
2248
| ------ | ------ | ---- | ---- | ---------------------------------------- |                        
A
Annie_wang 已提交
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
| ino    | number | Yes   | No   | File ID. Different files on the same device have different **ino**s.|                 |
| mode   | number | Yes   | No   | File permissions. The meaning of each bit is as follows:<br>- **0o400**: The owner has the read permission on 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 read permission on 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 read 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.|
| 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 已提交
2269 2270 2271
  | Type     | Description              |
  | ------- | ---------------- |
  | boolean | Whether the file is a block special file.|
A
Annie_wang 已提交
2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289

**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 已提交
2290 2291 2292
  | Type     | Description               |
  | ------- | ----------------- |
  | boolean | Whether the file is a character special file.|
A
Annie_wang 已提交
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311

**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 已提交
2312 2313 2314
  | Type     | Description           |
  | ------- | ------------- |
  | boolean | Whether the file is a directory.|
A
Annie_wang 已提交
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333

**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 已提交
2334 2335 2336
  | Type     | Description                   |
  | ------- | --------------------- |
  | boolean | Whether the file is a FIFO.|
A
Annie_wang 已提交
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355

**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 已提交
2356 2357 2358
  | Type     | Description             |
  | ------- | --------------- |
  | boolean | Whether the file is a regular file.|
A
Annie_wang 已提交
2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377

**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 已提交
2378 2379 2380
  | Type     | Description            |
  | ------- | -------------- |
  | boolean | Whether the file is a socket.|
A
Annie_wang 已提交
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399

**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 已提交
2400 2401 2402
  | Type     | Description             |
  | ------- | --------------- |
  | boolean | Whether the file is a symbolic link.|
A
Annie_wang 已提交
2403 2404 2405 2406 2407 2408 2409 2410 2411 2412

**Example**

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

## Stream

A
Annie_wang 已提交
2413
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 已提交
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425


### 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 已提交
2426 2427 2428
  | Type                 | Description           |
  | ------------------- | ------------- |
  | Promise&lt;void&gt; | Promise used to return the stream close result.|
A
Annie_wang 已提交
2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452

**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 已提交
2453 2454 2455
  | Name     | Type                       | Mandatory  | Description           |
  | -------- | ------------------------- | ---- | ------------- |
  | callback | AsyncCallback&lt;void&gt; | Yes   | Callback invoked when the stream is closed asynchronously.|
A
Annie_wang 已提交
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496

**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 {
      console.info("close stream success"):
    }
  });
  ```

### closeSync

closeSync(): void

Synchronously closes the stream.

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

**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 已提交
2497 2498 2499
  | Type                 | Description           |
  | ------------------- | ------------- |
  | Promise&lt;void&gt; | Promise used to return the stream flushing result.|
A
Annie_wang 已提交
2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523

**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 已提交
2524 2525 2526
  | Name     | Type                       | Mandatory  | Description            |
  | -------- | ------------------------- | ---- | -------------- |
  | callback | AsyncCallback&lt;void&gt; | Yes   | Callback invoked when the stream is asynchronously flushed.|
A
Annie_wang 已提交
2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567

**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

**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 已提交
2568 2569 2570 2571
  | 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 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 已提交
2572 2573 2574

**Return value**

A
Annie_wang 已提交
2575 2576 2577
  | Type                   | Description      |
  | --------------------- | -------- |
  | Promise&lt;number&gt; | Promise used to return the length of the data written.|
A
Annie_wang 已提交
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601

**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 已提交
2602 2603 2604 2605 2606
  | 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 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.|
  | callback | AsyncCallback&lt;number&gt;     | Yes  | Callback invoked when the data is written asynchronously.                              |
A
Annie_wang 已提交
2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633

**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 已提交
2634 2635 2636 2637
  | 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 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 已提交
2638 2639 2640

**Return value**

A
Annie_wang 已提交
2641 2642 2643
  | Type    | Description      |
  | ------ | -------- |
  | number | Length of the data written in the file.|
A
Annie_wang 已提交
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662

**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 已提交
2663 2664 2665 2666
  | 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): position of the data to read in the file. By default, data is read from the current position.|
A
Annie_wang 已提交
2667 2668 2669

**Return value**

A
Annie_wang 已提交
2670 2671 2672
  | Type                                | Description    |
  | ---------------------------------- | ------ |
  | Promise&lt;number&gt; | Promise used to return the data read.|
A
Annie_wang 已提交
2673 2674 2675 2676 2677 2678 2679 2680 2681

**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 已提交
2682
    console.log(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen))));
A
Annie_wang 已提交
2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
  }).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 已提交
2699 2700 2701 2702 2703
  | 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): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.|
  | callback | AsyncCallback&lt;number&gt; | Yes   | Callback invoked when data is read asynchronously from the stream.                        |
A
Annie_wang 已提交
2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715

**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 已提交
2716
      console.log(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen))));
A
Annie_wang 已提交
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
    }
  });
  ```

### 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 已提交
2731 2732 2733
  | Name    | Type         | Mandatory  | Description                                      |
  | ------- | ----------- | ---- | ---------------------------------------- |
  | buffer  | ArrayBuffer | Yes   | Buffer used to store the file read.                             |
A
Annie_wang 已提交
2734
  | 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): position of the data to read in the file. By default, data is read from the current position.<br> |
A
Annie_wang 已提交
2735 2736 2737

**Return value**

A
Annie_wang 已提交
2738 2739 2740
  | Type    | Description      |
  | ------ | -------- |
  | number | Length of the data read.|
A
Annie_wang 已提交
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761

**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 已提交
2762 2763
### lock

A
Annie_wang 已提交
2764
lock(exclusive?: boolean): Promise\<void>
A
Annie_wang 已提交
2765 2766 2767 2768 2769 2770 2771

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 已提交
2772 2773 2774
  | 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 已提交
2775 2776 2777

**Return value**

A
Annie_wang 已提交
2778 2779 2780
  | Type                                | Description    |
  | ---------------------------------- | ------ |
  | Promise&lt;void&gt; | Promise that returns no value.|
A
Annie_wang 已提交
2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794

**Example**

  ```js
  let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  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 已提交
2795
lock(exclusive?: boolean, callback: AsyncCallback\<void>): void
A
Annie_wang 已提交
2796 2797 2798 2799 2800 2801 2802

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 已提交
2803 2804 2805 2806
  | 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 已提交
2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822

**Example**

  ```js
  let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  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 已提交
2823
tryLock(exclusive?: boolean): void
A
Annie_wang 已提交
2824 2825 2826 2827 2828 2829 2830

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 已提交
2831 2832 2833
  | 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 已提交
2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844

**Example**

  ```js
  let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  file.tryLock(true);
  console.log("lock file successful");
  ```

### unlock

A
Annie_wang 已提交
2845
unlock(): void
A
Annie_wang 已提交
2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859

Unlocks this file synchronously.

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

**Example**

  ```js
  let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  file.tryLock(true);
  file.unlock();
  console.log("unlock file successful");
  ```

A
Annie_wang 已提交
2860 2861
## Watcher<sup>10+</sup>

A
Annie_wang 已提交
2862
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 已提交
2863 2864 2865 2866 2867

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

start(): void

A
Annie_wang 已提交
2868
Starts listening.
A
Annie_wang 已提交
2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886

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

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

**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 已提交
2887
Stops listening.
A
Annie_wang 已提交
2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901

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

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

**Example**

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

A
Annie_wang 已提交
2902 2903
## OpenMode

A
Annie_wang 已提交
2904
Defines the constants of the **mode** parameter used in **open()**. It specifies the mode for opening a file.
A
Annie_wang 已提交
2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919

**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 已提交
2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934

## Filter

**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**.      |