1# @ohos.file.fs (File Management) 2 3The **fs** module provides APIs for file operations, including basic file management, directory management, file information statistics, and data read and write using a stream. 4 5> **NOTE** 6> 7> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. 8 9## Modules to Import 10 11```js 12import fs from '@ohos.file.fs'; 13``` 14 15## Guidelines 16 17Before using the APIs provided by this module to perform operations on a file or directory, obtain the application sandbox path of the file or directory as follows: 18 19**Stage Model** 20 21 ```js 22import UIAbility from '@ohos.app.ability.UIAbility'; 23 24export default class EntryAbility extends UIAbility { 25 onWindowStageCreate(windowStage) { 26 let context = this.context; 27 let pathDir = context.filesDir; 28 } 29} 30 ``` 31 32**FA Model** 33 34 ```js 35 import featureAbility from '@ohos.ability.featureAbility'; 36 37 let context = featureAbility.getContext(); 38 context.getFilesDir().then((data) => { 39 let pathDir = data; 40 }) 41 ``` 42 43For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context). 44 45## fs.stat 46 47stat(file: string|number): Promise<Stat> 48 49Obtains detailed file information. This API uses a promise to return the result. 50 51**System capability**: SystemCapability.FileManagement.File.FileIO 52 53**Parameters** 54 55| Name| Type | Mandatory| Description | 56| ------ | ------ | ---- | -------------------------- | 57| file | string\|number | Yes | Application sandbox path or file descriptor (FD) of the file.| 58 59**Return value** 60 61 | Type | Description | 62 | ---------------------------- | ---------- | 63 | Promise<[Stat](#stat)> | Promise used to return the file information obtained.| 64 65**Error codes** 66 67For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 68 69**Example** 70 71 ```js 72 let filePath = pathDir + "/test.txt"; 73 fs.stat(filePath).then((stat) => { 74 console.info("get file info succeed, the size of file is " + stat.size); 75 }).catch((err) => { 76 console.info("get file info failed with error message: " + err.message + ", error code: " + err.code); 77 }); 78 ``` 79 80## fs.stat 81 82stat(file: string|number, callback: AsyncCallback<Stat>): void 83 84Obtains detailed file information. This API uses an asynchronous callback to return the result. 85 86**System capability**: SystemCapability.FileManagement.File.FileIO 87 88**Parameters** 89 90| Name | Type | Mandatory| Description | 91| -------- | ---------------------------------- | ---- | ------------------------------ | 92| file | string\|number | Yes | Application sandbox path or FD of the file. | 93| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the file information obtained.| 94 95**Error codes** 96 97For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 98 99**Example** 100 101 ```js 102 fs.stat(pathDir, (err, stat) => { 103 if (err) { 104 console.info("get file info failed with error message: " + err.message + ", error code: " + err.code); 105 } else { 106 console.info("get file info succeed, the size of file is " + stat.size); 107 } 108 }); 109 ``` 110 111## fs.statSync 112 113statSync(file: string|number): Stat 114 115Obtains detailed file information synchronously. 116 117**System capability**: SystemCapability.FileManagement.File.FileIO 118 119**Parameters** 120 121| Name| Type | Mandatory| Description | 122| ------ | ------ | ---- | -------------------------- | 123| file | string\|number | Yes | Application sandbox path or FD of the file.| 124 125**Return value** 126 127 | Type | Description | 128 | ------------- | ---------- | 129 | [Stat](#stat) | File information obtained.| 130 131**Error codes** 132 133For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 134 135**Example** 136 137 ```js 138 let stat = fs.statSync(pathDir); 139 console.info("get file info succeed, the size of file is " + stat.size); 140 ``` 141 142## fs.access 143 144access(path: string): Promise<boolean> 145 146Checks whether a file exists. This API uses a promise to return the result. 147 148**System capability**: SystemCapability.FileManagement.File.FileIO 149 150**Parameters** 151 152| Name| Type | Mandatory| Description | 153| ------ | ------ | ---- | ------------------------------------------------------------ | 154| path | string | Yes | Application sandbox path of the file. | 155 156**Return value** 157 158 | Type | Description | 159 | ------------------- | ---------------------------- | 160 | Promise<boolean> | Promise used to return the result. The value **true** means the file exists; the value **false** means the opposite.| 161 162**Error codes** 163 164For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 165 166**Example** 167 168 ```js 169 let filePath = pathDir + "/test.txt"; 170 fs.access(filePath).then((res) => { 171 if (res) { 172 console.info("file exists"); 173 } 174 }).catch((err) => { 175 console.info("access failed with error message: " + err.message + ", error code: " + err.code); 176 }); 177 ``` 178 179## fs.access 180 181access(path: string, callback: AsyncCallback<boolean>): void 182 183Checks whether a file exists. This API uses an asynchronous callback to return the result. 184 185**System capability**: SystemCapability.FileManagement.File.FileIO 186 187**Parameters** 188 189| Name | Type | Mandatory| Description | 190| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 191| path | string | Yes | Application sandbox path of the file. | 192| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the file exists; the value **false** means the opposite.| 193 194**Error codes** 195 196For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 197 198**Example** 199 200 ```js 201 let filePath = pathDir + "/test.txt"; 202 fs.access(filePath, (err, res) => { 203 if (err) { 204 console.info("access failed with error message: " + err.message + ", error code: " + err.code); 205 } else { 206 if (res) { 207 console.info("file exists"); 208 } 209 } 210 }); 211 ``` 212 213## fs.accessSync 214 215accessSync(path: string): boolean 216 217Synchronously checks whether a file exists. 218 219**System capability**: SystemCapability.FileManagement.File.FileIO 220 221**Parameters** 222 223| Name| Type | Mandatory| Description | 224| ------ | ------ | ---- | ------------------------------------------------------------ | 225| path | string | Yes | Application sandbox path of the file. | 226 227**Return value** 228 229 | Type | Description | 230 | ------------------- | ---------------------------- | 231 | boolean | Returns **true** if the file exists; returns **false** otherwise.| 232 233**Error codes** 234 235For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 236 237**Example** 238 239 ```js 240 let filePath = pathDir + "/test.txt"; 241 try { 242 let res = fs.accessSync(filePath); 243 if (res) { 244 console.info("file exists"); 245 } 246 } catch(err) { 247 console.info("accessSync failed with error message: " + err.message + ", error code: " + err.code); 248 } 249 ``` 250 251 252## fs.close 253 254close(file: File|number): Promise<void> 255 256Closes a file. This API uses a promise to return the result. 257 258**System capability**: SystemCapability.FileManagement.File.FileIO 259 260**Parameters** 261 262 | Name | Type | Mandatory | Description | 263 | ---- | ------ | ---- | ------------ | 264 | file | [File](#file)\|number | Yes | File object or FD of the file to close.| 265 266**Return value** 267 268 | Type | Description | 269 | ------------------- | ---------------------------- | 270 | Promise<void> | Promise that returns no value.| 271 272**Error codes** 273 274For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 275 276**Example** 277 278 ```js 279 let filePath = pathDir + "/test.txt"; 280 let file = fs.openSync(filePath); 281 fs.close(file).then(() => { 282 console.info("File closed"); 283 fs.closeSync(file); 284 }).catch((err) => { 285 console.info("close file failed with error message: " + err.message + ", error code: " + err.code); 286 }); 287 ``` 288 289## fs.close 290 291close(file: File|number, callback: AsyncCallback<void>): void 292 293Closes a file. This API uses an asynchronous callback to return the result. 294 295**System capability**: SystemCapability.FileManagement.File.FileIO 296 297**Parameters** 298 299 | Name | Type | Mandatory | Description | 300 | -------- | ------------------------- | ---- | ------------ | 301 | file | [File](#file)\|number | Yes | File object or FD of the file to close.| 302 | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is closed.| 303 304**Error codes** 305 306For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 307 308**Example** 309 310 ```js 311 let filePath = pathDir + "/test.txt"; 312 let file = fs.openSync(filePath); 313 fs.close(file, (err) => { 314 if (err) { 315 console.info("close file failed with error message: " + err.message + ", error code: " + err.code); 316 } else { 317 console.info("close file success"); 318 } 319 }); 320 ``` 321 322## fs.closeSync 323 324closeSync(file: File|number): void 325 326Synchronously closes a file. 327 328**System capability**: SystemCapability.FileManagement.File.FileIO 329 330**Parameters** 331 332 | Name | Type | Mandatory | Description | 333 | ---- | ------ | ---- | ------------ | 334 | file | [File](#file)\|number | Yes | File object or FD of the file to close.| 335 336**Error codes** 337 338For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 339 340**Example** 341 342 ```js 343 let filePath = pathDir + "/test.txt"; 344 let file = fs.openSync(filePath); 345 fs.closeSync(file); 346 ``` 347 348## fs.copyFile 349 350copyFile(src: string|number, dest: string|number, mode?: number): Promise<void> 351 352Copies a file. This API uses a promise to return the result. 353 354**System capability**: SystemCapability.FileManagement.File.FileIO 355 356**Parameters** 357 358 | Name | Type | Mandatory | Description | 359 | ---- | -------------------------- | ---- | ---------------------------------------- | 360 | src | string\|number | Yes | Path or FD of the file to copy. | 361 | dest | string\|number | Yes | Destination path of the file or FD of the file created. | 362 | mode | number | No | Whether to overwrite the file with the same name in the destination directory. The default value is **0**, which is the only value supported.<br>**0**: overwrite the file with the same name.| 363 364**Return value** 365 366 | Type | Description | 367 | ------------------- | ---------------------------- | 368 | Promise<void> | Promise that returns no value.| 369 370**Error codes** 371 372For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 373 374**Example** 375 376 ```js 377 let srcPath = pathDir + "/srcDir/test.txt"; 378 let dstPath = pathDir + "/dstDir/test.txt"; 379 fs.copyFile(srcPath, dstPath).then(() => { 380 console.info("copy file succeed"); 381 }).catch((err) => { 382 console.info("copy file failed with error message: " + err.message + ", error code: " + err.code); 383 }); 384 ``` 385 386## fs.copyFile 387 388copyFile(src: string|number, dest: string|number, mode?: number, callback: AsyncCallback<void>): void 389 390Copies a file. This API uses an asynchronous callback to return the result. 391 392**System capability**: SystemCapability.FileManagement.File.FileIO 393 394**Parameters** 395 396 | Name | Type | Mandatory | Description | 397 | -------- | -------------------------- | ---- | ---------------------------------------- | 398 | src | string\|number | Yes | Path or FD of the file to copy. | 399 | dest | string\|number | Yes | Destination path of the file or FD of the file created. | 400 | mode | number | No | Whether to overwrite the file with the same name in the destination directory. The default value is **0**, which is the only value supported.<br>**0**: overwrite the file with the same name and truncate the part that is not overwritten.| 401 | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is copied. | 402 403**Error codes** 404 405For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 406 407**Example** 408 409 ```js 410 let srcPath = pathDir + "/srcDir/test.txt"; 411 let dstPath = pathDir + "/dstDir/test.txt"; 412 fs.copyFile(srcPath, dstPath, (err) => { 413 if (err) { 414 console.info("copy file failed with error message: " + err.message + ", error code: " + err.code); 415 } else { 416 console.info("copy file success"); 417 } 418 }); 419 ``` 420 421 422## fs.copyFileSync 423 424copyFileSync(src: string|number, dest: string|number, mode?: number): void 425 426Synchronously copies a file. 427 428**System capability**: SystemCapability.FileManagement.File.FileIO 429 430**Parameters** 431 432 | Name | Type | Mandatory | Description | 433 | ---- | -------------------------- | ---- | ---------------------------------------- | 434 | src | string\|number | Yes | Path or FD of the file to copy. | 435 | dest | string\|number | Yes | Destination path of the file or FD of the file created. | 436 | mode | number | No | Whether to overwrite the file with the same name in the destination directory. The default value is **0**, which is the only value supported.<br>**0**: overwrite the file with the same name and truncate the part that is not overwritten.| 437 438**Error codes** 439 440For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 441 442**Example** 443 444 ```js 445 let srcPath = pathDir + "/srcDir/test.txt"; 446 let dstPath = pathDir + "/dstDir/test.txt"; 447 fs.copyFileSync(srcPath, dstPath); 448 ``` 449 450## fs.mkdir 451 452mkdir(path: string): Promise<void> 453 454Creates a directory. This API uses a promise to return the result. 455 456**System capability**: SystemCapability.FileManagement.File.FileIO 457 458**Parameters** 459 460| Name| Type | Mandatory| Description | 461| ------ | ------ | ---- | ------------------------------------------------------------ | 462| path | string | Yes | Application sandbox path of the directory. | 463 464**Return value** 465 466 | Type | Description | 467 | ------------------- | ---------------------------- | 468 | Promise<void> | Promise that returns no value.| 469 470**Error codes** 471 472For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 473 474**Example** 475 476 ```js 477 let dirPath = pathDir + "/testDir"; 478 fs.mkdir(dirPath).then(() => { 479 console.info("Directory created"); 480 }).catch((err) => { 481 console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); 482 }); 483 ``` 484 485## fs.mkdir 486 487mkdir(path: string, callback: AsyncCallback<void>): void 488 489Creates a directory. This API uses an asynchronous callback to return the result. 490 491**System capability**: SystemCapability.FileManagement.File.FileIO 492 493**Parameters** 494 495| Name | Type | Mandatory| Description | 496| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 497| path | string | Yes | Application sandbox path of the directory. | 498| callback | AsyncCallback<void> | Yes | Callback invoked when the directory is created asynchronously. | 499 500**Error codes** 501 502For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 503 504**Example** 505 506 ```js 507 let dirPath = pathDir + "/testDir"; 508 fs.mkdir(dirPath, (err) => { 509 if (err) { 510 console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); 511 } else { 512 console.info("mkdir success"); 513 } 514 }); 515 ``` 516 517## fs.mkdirSync 518 519mkdirSync(path: string): void 520 521Synchronously creates a directory. 522 523**System capability**: SystemCapability.FileManagement.File.FileIO 524 525**Parameters** 526 527| Name| Type | Mandatory| Description | 528| ------ | ------ | ---- | ------------------------------------------------------------ | 529| path | string | Yes | Application sandbox path of the directory. | 530 531**Error codes** 532 533For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 534 535**Example** 536 537 ```js 538 let dirPath = pathDir + "/testDir"; 539 fs.mkdirSync(dirPath); 540 ``` 541 542## fs.open 543 544open(path: string, mode?: number): Promise<File> 545 546Opens a file. This API uses a promise to return the result. File uniform resource identifiers (URIs) are supported. 547 548**System capability**: SystemCapability.FileManagement.File.FileIO 549 550**Parameters** 551 552| Name| Type | Mandatory| Description | 553| ------ | ------ | ---- | ------------------------------------------------------------ | 554| path | string | Yes | Application sandbox path or URI of the file. | 555| 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 (|). 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.| 556 557**Return value** 558 559 | Type | Description | 560 | --------------------- | ----------- | 561 | Promise<[File](#file)> | Promise used to return the file object.| 562 563**Error codes** 564 565For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 566 567**Example** 568 569 ```js 570 let filePath = pathDir + "/test.txt"; 571 fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE).then((file) => { 572 console.info("file fd: " + file.fd); 573 }).catch((err) => { 574 console.info("open file failed with error message: " + err.message + ", error code: " + err.code); 575 }); 576 ``` 577 578 579## fs.open 580 581open(path: string, mode?: number, callback: AsyncCallback<File>): void 582 583Opens a file. This API uses an asynchronous callback to return the result. File URIs are supported. 584 585**System capability**: SystemCapability.FileManagement.File.FileIO 586 587**Parameters** 588 589| Name | Type | Mandatory| Description | 590| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | 591| path | string | Yes | Application sandbox path or URI of the file. | 592| 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 (|). 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.| 593 594**Error codes** 595 596For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 597 598**Example** 599 600 ```js 601 let filePath = pathDir + "/test.txt"; 602 fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE, (err, file) => { 603 if (err) { 604 console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); 605 } else { 606 console.info("file fd: " + file.fd); 607 } 608 }); 609 ``` 610 611## fs.openSync 612 613openSync(path: string, mode?: number): File 614 615Synchronously opens a file. File URIs are supported. 616 617**System capability**: SystemCapability.FileManagement.File.FileIO 618 619**Parameters** 620 621| Name| Type | Mandatory| Description | 622| ------ | ------ | ---- | ------------------------------------------------------------ | 623| path | string | Yes | Application sandbox path or URI of the file. | 624| 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 (|). 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.| 625 626**Return value** 627 628 | Type | Description | 629 | ------ | ----------- | 630 | [File](#file) | File object opened.| 631 632**Error codes** 633 634For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 635 636**Example** 637 638 ```js 639 let filePath = pathDir + "/test.txt"; 640 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 641 console.info("file fd: " + file.fd); 642 fs.closeSync(file); 643 ``` 644 645## fs.read 646 647read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): Promise<number> 648 649Reads data from a file. This API uses a promise to return the result. 650 651**System capability**: SystemCapability.FileManagement.File.FileIO 652 653**Parameters** 654 655| Name | Type | Mandatory| Description | 656| ------- | ----------- | ---- | ------------------------------------------------------------ | 657| fd | number | Yes | FD of the file. | 658| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | 659| 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.| 660 661**Return value** 662 663 | Type | Description | 664 | ---------------------------------- | ------ | 665 | Promise<number> | Promise used to return the data read.| 666 667**Error codes** 668 669For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 670 671**Example** 672 673 ```js 674 let filePath = pathDir + "/test.txt"; 675 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 676 let buf = new ArrayBuffer(4096); 677 fs.read(file.fd, buf).then((readLen) => { 678 console.info("Read file data successfully"); 679 console.info(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))); 680 fs.closeSync(file); 681 }).catch((err) => { 682 console.info("read file data failed with error message: " + err.message + ", error code: " + err.code); 683 }); 684 ``` 685 686## fs.read 687 688read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }, callback: AsyncCallback<number>): void 689 690Reads data from a file. This API uses an asynchronous callback to return the result. 691 692**System capability**: SystemCapability.FileManagement.File.FileIO 693 694**Parameters** 695 696 | Name | Type | Mandatory | Description | 697 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 698 | fd | number | Yes | FD of the file. | 699 | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | 700 | 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.| 701 | callback | AsyncCallback<number> | Yes | Callback invoked when the data is read asynchronously. | 702 703**Error codes** 704 705For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 706 707**Example** 708 709 ```js 710 let filePath = pathDir + "/test.txt"; 711 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 712 let buf = new ArrayBuffer(4096); 713 fs.read(file.fd, buf, (err, readLen) => { 714 if (err) { 715 console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); 716 } else { 717 console.info("Read file data successfully"); 718 console.info(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))); 719 fs.closeSync(file); 720 } 721 }); 722 ``` 723 724## fs.readSync 725 726readSync(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number 727 728Synchronously reads data from a file. 729 730**System capability**: SystemCapability.FileManagement.File.FileIO 731 732**Parameters** 733 734 | Name | Type | Mandatory | Description | 735 | ------- | ----------- | ---- | ---------------------------------------- | 736 | fd | number | Yes | FD of the file. | 737 | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | 738 | 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.| 739 740**Return value** 741 742 | Type | Description | 743 | ------ | -------- | 744 | number | Length of the data read.| 745 746**Error codes** 747 748For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 749 750**Example** 751 752 ```js 753 let filePath = pathDir + "/test.txt"; 754 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 755 let buf = new ArrayBuffer(4096); 756 let num = fs.readSync(file.fd, buf); 757 fs.closeSync(file); 758 ``` 759 760## fs.rmdir 761 762rmdir(path: string): Promise<void> 763 764Deletes a directory. This API uses a promise to return the result. 765 766**System capability**: SystemCapability.FileManagement.File.FileIO 767 768**Parameters** 769 770| Name| Type | Mandatory| Description | 771| ------ | ------ | ---- | -------------------------- | 772| path | string | Yes | Application sandbox path of the directory.| 773 774**Return value** 775 776 | Type | Description | 777 | ------------------- | ---------------------------- | 778 | Promise<void> | Promise that returns no value.| 779 780**Error codes** 781 782For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 783 784**Example** 785 786 ```js 787 let dirPath = pathDir + "/testDir"; 788 fs.rmdir(dirPath).then(() => { 789 console.info("Directory deleted"); 790 }).catch((err) => { 791 console.info("rmdir failed with error message: " + err.message + ", error code: " + err.code); 792 }); 793 ``` 794 795## fs.rmdir 796 797rmdir(path: string, callback: AsyncCallback<void>): void 798 799Deletes a directory. This API uses an asynchronous callback to return the result. 800 801**System capability**: SystemCapability.FileManagement.File.FileIO 802 803**Parameters** 804 805| Name | Type | Mandatory| Description | 806| -------- | ------------------------- | ---- | -------------------------- | 807| path | string | Yes | Application sandbox path of the directory.| 808| callback | AsyncCallback<void> | Yes | Callback invoked when the directory is deleted asynchronously. | 809 810**Error codes** 811 812For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 813 814**Example** 815 816 ```js 817 let dirPath = pathDir + "/testDir"; 818 fs.rmdir(dirPath, (err) => { 819 if (err) { 820 console.info("rmdir failed with error message: " + err.message + ", error code: " + err.code); 821 } else { 822 console.info("Directory deleted"); 823 } 824 }); 825 ``` 826 827## fs.rmdirSync 828 829rmdirSync(path: string): void 830 831Synchronously deletes a directory. 832 833**System capability**: SystemCapability.FileManagement.File.FileIO 834 835**Parameters** 836 837| Name| Type | Mandatory| Description | 838| ------ | ------ | ---- | -------------------------- | 839| path | string | Yes | Application sandbox path of the directory.| 840 841**Error codes** 842 843For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 844 845**Example** 846 847 ```js 848 let dirPath = pathDir + "/testDir"; 849 fs.rmdirSync(dirPath); 850 ``` 851 852## fs.unlink 853 854unlink(path: string): Promise<void> 855 856Deletes a file. This API uses a promise to return the result. 857 858**System capability**: SystemCapability.FileManagement.File.FileIO 859 860**Parameters** 861 862| Name| Type | Mandatory| Description | 863| ------ | ------ | ---- | -------------------------- | 864| path | string | Yes | Application sandbox path of the file.| 865 866**Return value** 867 868 | Type | Description | 869 | ------------------- | ---------------------------- | 870 | Promise<void> | Promise that returns no value.| 871 872**Error codes** 873 874For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 875 876**Example** 877 878 ```js 879 let filePath = pathDir + "/test.txt"; 880 fs.unlink(filePath).then(() => { 881 console.info("File deleted"); 882 }).catch((err) => { 883 console.info("remove file failed with error message: " + err.message + ", error code: " + err.codeor); 884 }); 885 ``` 886 887## fs.unlink 888 889unlink(path: string, callback: AsyncCallback<void>): void 890 891Deletes a file. This API uses an asynchronous callback to return the result. 892 893**System capability**: SystemCapability.FileManagement.File.FileIO 894 895**Parameters** 896 897| Name | Type | Mandatory| Description | 898| -------- | ------------------------- | ---- | -------------------------- | 899| path | string | Yes | Application sandbox path of the file.| 900| callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is deleted. | 901 902**Error codes** 903 904For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 905 906**Example** 907 908 ```js 909 let filePath = pathDir + "/test.txt"; 910 fs.unlink(filePath, (err) => { 911 if (err) { 912 console.info("remove file failed with error message: " + err.message + ", error code: " + err.code); 913 } else { 914 console.info("File deleted"); 915 } 916 }); 917 ``` 918 919## fs.unlinkSync 920 921unlinkSync(path: string): void 922 923Synchronously deletes a file. 924 925**System capability**: SystemCapability.FileManagement.File.FileIO 926 927**Parameters** 928 929| Name| Type | Mandatory| Description | 930| ------ | ------ | ---- | -------------------------- | 931| path | string | Yes | Application sandbox path of the file.| 932 933**Error codes** 934 935For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 936 937**Example** 938 939 ```js 940 let filePath = pathDir + "/test.txt"; 941 fs.unlinkSync(filePath); 942 ``` 943 944 945## fs.write 946 947write(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): Promise<number> 948 949Writes data into a file. This API uses a promise to return the result. 950 951**System capability**: SystemCapability.FileManagement.File.FileIO 952 953**Parameters** 954 955 | Name | Type | Mandatory | Description | 956 | ------- | ------------------------------- | ---- | ---------------------------------------- | 957 | fd | number | Yes | FD of the file. | 958 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 959 | 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.| 960 961**Return value** 962 963 | Type | Description | 964 | --------------------- | -------- | 965 | Promise<number> | Promise used to return the length of the data written.| 966 967**Error codes** 968 969For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 970 971**Example** 972 973 ```js 974 let filePath = pathDir + "/test.txt"; 975 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 976 fs.write(file.fd, "hello, world").then((writeLen) => { 977 console.info("write data to file succeed and size is:" + writeLen); 978 fs.closeSync(file); 979 }).catch((err) => { 980 console.info("write data to file failed with error message: " + err.message + ", error code: " + err.code); 981 }); 982 ``` 983 984## fs.write 985 986write(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback<number>): void 987 988Writes data into a file. This API uses an asynchronous callback to return the result. 989 990**System capability**: SystemCapability.FileManagement.File.FileIO 991 992**Parameters** 993 994 | Name | Type | Mandatory | Description | 995 | -------- | ------------------------------- | ---- | ---------------------------------------- | 996 | fd | number | Yes | FD of the file. | 997 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 998 | 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.| 999 | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | 1000 1001**Error codes** 1002 1003For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1004 1005**Example** 1006 1007 ```js 1008 let filePath = pathDir + "/test.txt"; 1009 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 1010 fs.write(file.fd, "hello, world", (err, writeLen) => { 1011 if (err) { 1012 console.info("write failed with error message: " + err.message + ", error code: " + err.code); 1013 } else { 1014 console.info("write data to file succeed and size is:" + writeLen); 1015 fs.closeSync(file); 1016 } 1017 }); 1018 ``` 1019 1020## fs.writeSync 1021 1022writeSync(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): number 1023 1024Synchronously writes data into a file. 1025 1026**System capability**: SystemCapability.FileManagement.File.FileIO 1027 1028**Parameters** 1029 1030 | Name | Type | Mandatory | Description | 1031 | ------- | ------------------------------- | ---- | ---------------------------------------- | 1032 | fd | number | Yes | FD of the file. | 1033 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 1034 | 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.| 1035 1036**Return value** 1037 1038 | Type | Description | 1039 | ------ | -------- | 1040 | number | Length of the data written in the file.| 1041 1042**Error codes** 1043 1044For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1045 1046**Example** 1047 1048 ```js 1049 let filePath = pathDir + "/test.txt"; 1050 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 1051 let writeLen = fs.writeSync(file.fd, "hello, world"); 1052 console.info("write data to file succeed and size is:" + writeLen); 1053 fs.closeSync(file); 1054 ``` 1055 1056## fs.truncate 1057 1058truncate(file: string|number, len?: number): Promise<void> 1059 1060Truncates a file. This API uses a promise to return the result. 1061 1062**System capability**: SystemCapability.FileManagement.File.FileIO 1063 1064**Parameters** 1065 1066| Name| Type | Mandatory| Description | 1067| ------ | ------ | ---- | -------------------------------- | 1068| file | string\|number | Yes | Application sandbox path or FD of the file. | 1069| len | number | No | File length, in bytes, after truncation. The default value is **0**.| 1070 1071**Return value** 1072 1073 | Type | Description | 1074 | ------------------- | ---------------------------- | 1075 | Promise<void> | Promise that returns no value.| 1076 1077**Error codes** 1078 1079For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1080 1081**Example** 1082 1083 ```js 1084 let filePath = pathDir + "/test.txt"; 1085 let len = 5; 1086 fs.truncate(filePath, len).then(() => { 1087 console.info("File truncated"); 1088 }).catch((err) => { 1089 console.info("truncate file failed with error message: " + err.message + ", error code: " + err.code); 1090 }); 1091 ``` 1092 1093## fs.truncate 1094 1095truncate(file: string|number, len?: number, callback: AsyncCallback<void>): void 1096 1097Truncates a file. This API uses an asynchronous callback to return the result. 1098 1099**System capability**: SystemCapability.FileManagement.File.FileIO 1100 1101**Parameters** 1102 1103| Name | Type | Mandatory| Description | 1104| -------- | ------------------------- | ---- | -------------------------------- | 1105| file | string\|number | Yes | Application sandbox path or FD of the file. | 1106| len | number | No | File length, in bytes, after truncation. The default value is **0**.| 1107| callback | AsyncCallback<void> | Yes | Callback that returns no value. | 1108 1109**Error codes** 1110 1111For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1112 1113**Example** 1114 1115 ```js 1116 let filePath = pathDir + "/test.txt"; 1117 let len = 5; 1118 fs.truncate(filePath, len, (err) => { 1119 if (err) { 1120 console.info("truncate failed with error message: " + err.message + ", error code: " + err.code); 1121 } else { 1122 console.info("truncate success"); 1123 } 1124 }); 1125 ``` 1126 1127## fs.truncateSync 1128 1129truncateSync(file: string|number, len?: number): void 1130 1131Synchronously truncates a file. 1132 1133**System capability**: SystemCapability.FileManagement.File.FileIO 1134 1135**Parameters** 1136 1137| Name| Type | Mandatory| Description | 1138| ------ | ------ | ---- | -------------------------------- | 1139| file | string\|number | Yes | Application sandbox path or FD of the file. | 1140| len | number | No | File length, in bytes, after truncation. The default value is **0**.| 1141 1142**Error codes** 1143 1144For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1145 1146**Example** 1147 1148 ```js 1149 let filePath = pathDir + "/test.txt"; 1150 let len = 5; 1151 fs.truncateSync(filePath, len); 1152 ``` 1153 1154## fs.readText 1155 1156readText(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }): Promise<string> 1157 1158Reads the text content of a file. This API uses a promise to return the result. 1159 1160**System capability**: SystemCapability.FileManagement.File.FileIO 1161 1162**Parameters** 1163 1164| Name | Type | Mandatory| Description | 1165| -------- | ------ | ---- | ------------------------------------------------------------ | 1166| filePath | string | Yes | Application sandbox path of the file. | 1167| 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.| 1168 1169**Return value** 1170 1171 | Type | Description | 1172 | --------------------- | ---------- | 1173 | Promise<string> | Promise used to return the content read.| 1174 1175**Error codes** 1176 1177For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1178 1179**Example** 1180 1181 ```js 1182 let filePath = pathDir + "/test.txt"; 1183 fs.readText(filePath).then((str) => { 1184 console.info("readText succeed:" + str); 1185 }).catch((err) => { 1186 console.info("readText failed with error message: " + err.message + ", error code: " + err.code); 1187 }); 1188 ``` 1189 1190## fs.readText 1191 1192readText(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback<string>): void 1193 1194Reads the text content of a file. This API uses an asynchronous callback to return the result. 1195 1196**System capability**: SystemCapability.FileManagement.File.FileIO 1197 1198**Parameters** 1199 1200| Name | Type | Mandatory| Description | 1201| -------- | --------------------------- | ---- | ------------------------------------------------------------ | 1202| filePath | string | Yes | Application sandbox path of the file. | 1203| 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.| 1204| callback | AsyncCallback<string> | Yes | Callback invoked to return the content read. | 1205 1206**Error codes** 1207 1208For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1209 1210**Example** 1211 1212 ```js 1213 let filePath = pathDir + "/test.txt"; 1214 fs.readText(filePath, { offset: 1, encoding: 'UTF-8' }, (err, str) => { 1215 if (err) { 1216 console.info("read text failed with error message: " + err.message + ", error code: " + err.code); 1217 } else { 1218 console.info("readText succeed:" + str); 1219 } 1220 }); 1221 ``` 1222 1223## fs.readTextSync 1224 1225readTextSync(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }): string 1226 1227Synchronously reads the text of a file. 1228 1229**System capability**: SystemCapability.FileManagement.File.FileIO 1230 1231**Parameters** 1232 1233| Name | Type | Mandatory| Description | 1234| -------- | ------ | ---- | ------------------------------------------------------------ | 1235| filePath | string | Yes | Application sandbox path of the file. | 1236| 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.| 1237 1238**Return value** 1239 1240 | Type | Description | 1241 | ------ | -------------------- | 1242 | string | Promise used to return the content of the file read.| 1243 1244**Error codes** 1245 1246For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1247 1248**Example** 1249 1250 ```js 1251 let filePath = pathDir + "/test.txt"; 1252 let str = fs.readTextSync(filePath, {offset: 1, length: 3}); 1253 console.info("readText succeed:" + str); 1254 ``` 1255 1256## fs.lstat 1257 1258lstat(path: string): Promise<Stat> 1259 1260Obtains information about a symbolic link. This API uses a promise to return the result. 1261 1262**System capability**: SystemCapability.FileManagement.File.FileIO 1263 1264**Parameters** 1265 1266| Name| Type | Mandatory| Description | 1267| ------ | ------ | ---- | -------------------------------------- | 1268| path | string | Yes | Application sandbox path of the file.| 1269 1270**Return value** 1271 1272 | Type | Description | 1273 | ---------------------------- | ---------- | 1274 | Promise<[Stat](#stat)> | Promise used to return the symbolic link information obtained. For details, see **stat**.| 1275 1276**Error codes** 1277 1278For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1279 1280**Example** 1281 1282 ```js 1283 let filePath = pathDir + "/test.txt"; 1284 fs.lstat(filePath).then((stat) => { 1285 console.info("get link status succeed, the size of file is" + stat.size); 1286 }).catch((err) => { 1287 console.info("get link status failed with error message: " + err.message + ", error code: " + err.code); 1288 }); 1289 ``` 1290 1291## fs.lstat 1292 1293lstat(path: string, callback: AsyncCallback<Stat>): void 1294 1295Obtains information about a symbolic link. This API uses an asynchronous callback to return the result. 1296 1297**System capability**: SystemCapability.FileManagement.File.FileIO 1298 1299**Parameters** 1300 1301| Name | Type | Mandatory| Description | 1302| -------- | ---------------------------------- | ---- | -------------------------------------- | 1303| path | string | Yes | Application sandbox path of the file.| 1304| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the symbolic link information obtained. | 1305 1306**Error codes** 1307 1308For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1309 1310**Example** 1311 1312 ```js 1313 let filePath = pathDir + "/test.txt"; 1314 fs.lstat(filePath, (err, stat) => { 1315 if (err) { 1316 console.info("lstat failed with error message: " + err.message + ", error code: " + err.code); 1317 } else { 1318 console.info("get link status succeed, the size of file is" + stat.size); 1319 } 1320 }); 1321 ``` 1322 1323## fs.lstatSync 1324 1325lstatSync(path: string): Stat 1326 1327Obtains information about a symbolic link synchronously. 1328 1329**System capability**: SystemCapability.FileManagement.File.FileIO 1330 1331**Parameters** 1332 1333| Name| Type | Mandatory| Description | 1334| ------ | ------ | ---- | -------------------------------------- | 1335| path | string | Yes | Application sandbox path of the file.| 1336 1337**Return value** 1338 1339 | Type | Description | 1340 | ------------- | ---------- | 1341 | [Stat](#stat) | File information obtained.| 1342 1343**Error codes** 1344 1345For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1346 1347**Example** 1348 1349 ```js 1350 let filePath = pathDir + "/test.txt"; 1351 let stat = fs.lstatSync(filePath); 1352 ``` 1353 1354## fs.rename 1355 1356rename(oldPath: string, newPath: string): Promise<void> 1357 1358Renames a file or directory. This API uses a promise to return the result. 1359 1360**System capability**: SystemCapability.FileManagement.File.FileIO 1361 1362**Parameters** 1363 1364| Name | Type | Mandatory| Description | 1365| ------- | ------ | ---- | ---------------------------- | 1366| oldPath | string | Yes | Application sandbox path of the file to rename.| 1367| newPath | string | Yes | Application sandbox path of the renamed file. | 1368 1369**Return value** 1370 1371 | Type | Description | 1372 | ------------------- | ---------------------------- | 1373 | Promise<void> | Promise that returns no value.| 1374 1375**Error codes** 1376 1377For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1378 1379**Example** 1380 1381 ```js 1382 let srcFile = pathDir + "/test.txt"; 1383 let dstFile = pathDir + "/new.txt"; 1384 fs.rename(srcFile, dstFile).then(() => { 1385 console.info("File renamed"); 1386 }).catch((err) => { 1387 console.info("rename failed with error message: " + err.message + ", error code: " + err.code); 1388 }); 1389 ``` 1390 1391## fs.rename 1392 1393rename(oldPath: string, newPath: string, callback: AsyncCallback<void>): void 1394 1395Renames a file or directory. This API uses an asynchronous callback to return the result. 1396 1397**System capability**: SystemCapability.FileManagement.File.FileIO 1398 1399**Parameters** 1400 1401| Name | Type | Mandatory| Description | 1402| -------- | ------------------------- | ---- | ---------------------------- | 1403| oldPath | string | Yes | Application sandbox path of the file to rename.| 1404| newPath | string | Yes | Application sandbox path of the renamed file. | 1405| callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously renamed. | 1406 1407**Error codes** 1408 1409For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1410 1411**Example** 1412 1413 ```js 1414 let srcFile = pathDir + "/test.txt"; 1415 let dstFile = pathDir + "/new.txt"; 1416 fs.rename(srcFile, dstFile, (err) => { 1417 if (err) { 1418 console.info("rename failed with error message: " + err.message + ", error code: " + err.code); 1419 } else { 1420 console.info("rename success"); 1421 } 1422 }); 1423 ``` 1424 1425## fs.renameSync 1426 1427renameSync(oldPath: string, newPath: string): void 1428 1429Renames a file or directory synchronously. 1430 1431**System capability**: SystemCapability.FileManagement.File.FileIO 1432 1433**Parameters** 1434 1435| Name | Type | Mandatory| Description | 1436| ------- | ------ | ---- | ---------------------------- | 1437| oldPath | string | Yes | Application sandbox path of the file to rename.| 1438| newPath | string | Yes | Application sandbox path of the renamed file. | 1439 1440**Error codes** 1441 1442For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1443 1444**Example** 1445 1446 ```js 1447 let srcFile = pathDir + "/test.txt"; 1448 let dstFile = pathDir + "/new.txt"; 1449 fs.renameSync(srcFile, dstFile); 1450 ``` 1451 1452## fs.fsync 1453 1454fsync(fd: number): Promise<void> 1455 1456Flushes data of a file to disk. This API uses a promise to return the result. 1457 1458**System capability**: SystemCapability.FileManagement.File.FileIO 1459 1460**Parameters** 1461 1462 | Name | Type | Mandatory | Description | 1463 | ---- | ------ | ---- | ------------ | 1464 | fd | number | Yes | FD of the file.| 1465 1466**Return value** 1467 1468 | Type | Description | 1469 | ------------------- | ---------------------------- | 1470 | Promise<void> | Promise that returns no value.| 1471 1472**Error codes** 1473 1474For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1475 1476**Example** 1477 1478 ```js 1479 let filePath = pathDir + "/test.txt"; 1480 let file = fs.openSync(filePath); 1481 fs.fsync(file.fd).then(() => { 1482 console.info("Data flushed"); 1483 }).catch((err) => { 1484 console.info("sync data failed with error message: " + err.message + ", error code: " + err.code); 1485 }); 1486 ``` 1487 1488## fs.fsync 1489 1490fsync(fd: number, callback: AsyncCallback<void>): void 1491 1492Flushes data of a file to disk. This API uses an asynchronous callback to return the result. 1493 1494**System capability**: SystemCapability.FileManagement.File.FileIO 1495 1496**Parameters** 1497 1498 | Name | Type | Mandatory | Description | 1499 | -------- | ------------------------- | ---- | --------------- | 1500 | fd | number | Yes | FD of the file. | 1501 | Callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| 1502 1503**Error codes** 1504 1505For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1506 1507**Example** 1508 1509 ```js 1510 let filePath = pathDir + "/test.txt"; 1511 let file = fs.openSync(filePath); 1512 fs.fsync(file.fd, (err) => { 1513 if (err) { 1514 console.info("fsync failed with error message: " + err.message + ", error code: " + err.code); 1515 } else { 1516 console.info("fsync success"); 1517 fs.closeSync(file); 1518 } 1519 }); 1520 ``` 1521 1522 1523## fs.fsyncSync 1524 1525fsyncSync(fd: number): void 1526 1527Flushes data of a file to disk synchronously. 1528 1529**System capability**: SystemCapability.FileManagement.File.FileIO 1530 1531**Parameters** 1532 1533 | Name | Type | Mandatory | Description | 1534 | ---- | ------ | ---- | ------------ | 1535 | fd | number | Yes | FD of the file.| 1536 1537**Error codes** 1538 1539For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1540 1541**Example** 1542 1543 ```js 1544 let filePath = pathDir + "/test.txt"; 1545 let file = fs.openSync(filePath); 1546 fs.fsyncSync(file.fd); 1547 fs.closeSync(file); 1548 ``` 1549 1550## fs.fdatasync 1551 1552fdatasync(fd: number): Promise<void> 1553 1554Flushes 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. 1555 1556**System capability**: SystemCapability.FileManagement.File.FileIO 1557 1558**Parameters** 1559 1560 | Name | Type | Mandatory | Description | 1561 | ---- | ------ | ---- | ------------ | 1562 | fd | number | Yes | FD of the file.| 1563 1564**Return value** 1565 1566 | Type | Description | 1567 | ------------------- | ---------------------------- | 1568 | Promise<void> | Promise that returns no value.| 1569 1570**Error codes** 1571 1572For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1573 1574**Example** 1575 1576 ```js 1577 let filePath = pathDir + "/test.txt"; 1578 let file = fs.openSync(filePath); 1579 fs.fdatasync(file.fd).then((err) => { 1580 console.info("Data flushed"); 1581 fs.closeSync(file); 1582 }).catch((err) => { 1583 console.info("sync data failed with error message: " + err.message + ", error code: " + err.code); 1584 }); 1585 ``` 1586 1587## fs.fdatasync 1588 1589fdatasync(fd: number, callback: AsyncCallback<void>): void 1590 1591Flushes data of a file to disk. This API uses an asynchronous callback to return the result. 1592 1593**System capability**: SystemCapability.FileManagement.File.FileIO 1594 1595**Parameters** 1596 1597 | Name | Type | Mandatory | Description | 1598 | -------- | ------------------------------- | ---- | ----------------- | 1599 | fd | number | Yes | FD of the file. | 1600 | callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| 1601 1602**Error codes** 1603 1604For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1605 1606**Example** 1607 1608 ```js 1609 let filePath = pathDir + "/test.txt"; 1610 let file = fs.openSync(filePath); 1611 fs.fdatasync (file.fd, (err) => { 1612 if (err) { 1613 console.info("fdatasync failed with error message: " + err.message + ", error code: " + err.code); 1614 } else { 1615 console.info("fdatasync success"); 1616 fs.closeSync(file); 1617 } 1618 }); 1619 ``` 1620 1621## fs.fdatasyncSync 1622 1623fdatasyncSync(fd: number): void 1624 1625Synchronizes data in a file synchronously. 1626 1627**System capability**: SystemCapability.FileManagement.File.FileIO 1628 1629**Parameters** 1630 1631 | Name | Type | Mandatory | Description | 1632 | ---- | ------ | ---- | ------------ | 1633 | fd | number | Yes | FD of the file.| 1634 1635**Error codes** 1636 1637For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1638 1639**Example** 1640 1641 ```js 1642 let filePath = pathDir + "/test.txt"; 1643 let file = fs.openSync(filePath); 1644 let stat = fs.fdatasyncSync(file.fd); 1645 fs.closeSync(file); 1646 ``` 1647 1648## fs.symlink 1649 1650symlink(target: string, srcPath: string): Promise<void> 1651 1652Creates a symbolic link based on a file path. This API uses a promise to return the result. 1653 1654**System capability**: SystemCapability.FileManagement.File.FileIO 1655 1656**Parameters** 1657 1658| Name | Type | Mandatory| Description | 1659| ------- | ------ | ---- | ---------------------------- | 1660| target | string | Yes | Application sandbox path of the source file. | 1661| srcPath | string | Yes | Application sandbox path of the symbolic link.| 1662 1663**Return value** 1664 1665 | Type | Description | 1666 | ------------------- | ---------------------------- | 1667 | Promise<void> | Promise that returns no value.| 1668 1669**Error codes** 1670 1671For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1672 1673**Example** 1674 1675 ```js 1676 let srcFile = pathDir + "/test.txt"; 1677 let dstFile = pathDir + "/test"; 1678 fs.symlink(srcFile, dstFile).then(() => { 1679 console.info("Symbolic link created"); 1680 }).catch((err) => { 1681 console.info("symlink failed with error message: " + err.message + ", error code: " + err.code); 1682 }); 1683 ``` 1684 1685 1686## fs.symlink 1687symlink(target: string, srcPath: string, callback: AsyncCallback<void>): void 1688 1689Creates a symbolic link based on a file path. This API uses an asynchronous callback to return the result. 1690 1691**System capability**: SystemCapability.FileManagement.File.FileIO 1692 1693**Parameters** 1694 1695| Name | Type | Mandatory| Description | 1696| -------- | ------------------------- | ---- | -------------------------------- | 1697| target | string | Yes | Application sandbox path of the source file. | 1698| srcPath | string | Yes | Application sandbox path of the symbolic link. | 1699| callback | AsyncCallback<void> | Yes | Callback invoked when the symbolic link is created asynchronously.| 1700 1701**Error codes** 1702 1703For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1704 1705**Example** 1706 1707 ```js 1708 let srcFile = pathDir + "/test.txt"; 1709 let dstFile = pathDir + "/test"; 1710 fs.symlink(srcFile, dstFile, (err) => { 1711 if (err) { 1712 console.info("symlink failed with error message: " + err.message + ", error code: " + err.code); 1713 } else { 1714 console.info("symlink success"); 1715 } 1716 }); 1717 ``` 1718 1719## fs.symlinkSync 1720 1721symlinkSync(target: string, srcPath: string): void 1722 1723Synchronously creates a symbolic link based on a file path. 1724 1725**System capability**: SystemCapability.FileManagement.File.FileIO 1726 1727**Parameters** 1728 1729| Name | Type | Mandatory| Description | 1730| ------- | ------ | ---- | ---------------------------- | 1731| target | string | Yes | Application sandbox path of the source file. | 1732| srcPath | string | Yes | Application sandbox path of the symbolic link.| 1733 1734**Error codes** 1735 1736For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1737 1738**Example** 1739 1740 ```js 1741 let srcFile = pathDir + "/test.txt"; 1742 let dstFile = pathDir + "/test"; 1743 fs.symlinkSync(srcFile, dstFile); 1744 ``` 1745 1746## fs.listFile 1747listFile(path: string, options?: { 1748 recursion?: boolean; 1749 listNum?: number; 1750 filter?: Filter; 1751}): Promise<string[]> 1752 1753Lists 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. 1754 1755**System capability**: SystemCapability.FileManagement.File.FileIO 1756 1757**Parameters** 1758 1759 | Name | Type | Mandatory | Description | 1760 | ------ | ------ | ---- | --------------------------- | 1761 | path | string | Yes | Application sandbox path of the folder.| 1762 | options | Object | No | File filtering options. The files are not filtered by default.| 1763 1764**options parameters** 1765 1766 | Name | Type | Mandatory | Description | 1767 | ------ | ------ | ---- | --------------------------- | 1768 | recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| 1769 | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| 1770 | 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.| 1771 1772**Return value** 1773 1774 | Type | Description | 1775 | --------------------- | ---------- | 1776 | Promise<string[]> | Promise used to return the files names listed.| 1777 1778**Error codes** 1779 1780For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1781 1782**Example** 1783 1784 ```js 1785 let options = { 1786 "recursion": false, 1787 "listNum": 0, 1788 "filter": { 1789 "suffix": [".png", ".jpg", ".jpeg"], 1790 "displayName": ["%abc", "efg%"], 1791 "fileSizeOver": 1024, 1792 "lastModifiedAfter": new Date().getTime(), 1793 } 1794 }; 1795 fs.listFile(pathDir, options).then((filenames) => { 1796 console.info("listFile succeed"); 1797 for (let i = 0; i < filenames.length; i++) { 1798 console.info("fileName: %s", filenames[i]); 1799 } 1800 }).catch((err) => { 1801 console.info("list file failed with error message: " + err.message + ", error code: " + err.code); 1802 }); 1803 ``` 1804 1805## fs.listFile 1806listFile(path: string, options?: { 1807 recursion?: boolean; 1808 listNum?: number; 1809 filter?: Filter; 1810}, callback: AsyncCallback<string[]>): void 1811 1812Lists 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. 1813 1814**Parameters** 1815 1816 | Name | Type | Mandatory | Description | 1817 | ------ | ------ | ---- | --------------------------- | 1818 | path | string | Yes | Application sandbox path of the folder.| 1819 | options | Object | No | File filtering options. The files are not filtered by default.| 1820 | callback | AsyncCallback<string[]> | Yes | Callback invoked to return the file names listed. | 1821 1822**options parameters** 1823 1824 | Name | Type | Mandatory | Description | 1825 | ------ | ------ | ---- | --------------------------- | 1826 | recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| 1827 | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| 1828 | 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.| 1829 1830**Error codes** 1831 1832For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1833 1834**Example** 1835 1836 ```js 1837 let options = { 1838 "recursion": false, 1839 "listNum": 0, 1840 "filter": { 1841 "suffix": [".png", ".jpg", ".jpeg"], 1842 "displayName": ["%abc", "efg%"], 1843 "fileSizeOver": 1024, 1844 "lastModifiedAfter": new Date().getTime(), 1845 } 1846 }; 1847 fs.listFile(pathDir, options, (err, filenames) => { 1848 if (err) { 1849 console.info("list file failed with error message: " + err.message + ", error code: " + err.code); 1850 } else { 1851 console.info("listFile succeed"); 1852 for (let i = 0; i < filenames.length; i++) { 1853 console.info("filename: %s", filenames[i]); 1854 } 1855 } 1856 }); 1857 ``` 1858 1859## fs.listFileSync 1860 1861listFileSync(path: string, options?: { 1862 recursion?: boolean; 1863 listNum?: number; 1864 filter?: Filter; 1865}): string[] 1866 1867Lists all files in a directory synchronously. This API supports recursive listing of all files (including files in subdirectories) and file filtering. 1868 1869**Parameters** 1870 1871 | Name | Type | Mandatory | Description | 1872 | ------ | ------ | ---- | --------------------------- | 1873 | path | string | Yes | Application sandbox path of the folder.| 1874 | options | Object | No | File filtering options. The files are not filtered by default.| 1875 1876**options parameters** 1877 1878 | Name | Type | Mandatory | Description | 1879 | ------ | ------ | ---- | --------------------------- | 1880 | recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| 1881 | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| 1882 | 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.| 1883 1884**Return value** 1885 1886 | Type | Description | 1887 | --------------------- | ---------- | 1888 | string[] | File names listed.| 1889 1890**Error codes** 1891 1892For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1893 1894**Example** 1895 1896 ```js 1897 let options = { 1898 "recursion": false, 1899 "listNum": 0, 1900 "filter": { 1901 "suffix": [".png", ".jpg", ".jpeg"], 1902 "displayName": ["%abc", "efg%"], 1903 "fileSizeOver": 1024, 1904 "lastModifiedAfter": new Date().getTime(), 1905 } 1906 }; 1907 let filenames = fs.listFileSync(pathDir, options); 1908 console.info("listFile succeed"); 1909 for (let i = 0; i < filenames.length; i++) { 1910 console.info("filename: %s", filenames[i]); 1911 } 1912 ``` 1913 1914## fs.moveFile 1915 1916moveFile(src: string, dest: string, mode?: number): Promise\<void> 1917 1918Moves a file. This API uses a promise to return the result. 1919 1920**System capability**: SystemCapability.FileManagement.File.FileIO 1921 1922**Parameters** 1923 1924 | Name | Type | Mandatory | Description | 1925 | ------ | ------ | ---- | --------------------------- | 1926 | src | string | Yes | Application sandbox path of the source file.| 1927 | dest | string | Yes | Application sandbox path of the destination file.| 1928 | mode | number | No | Whether to overwrite the file with the same name in the destination directory.<br> The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception.<br> The default value is **0**.| 1929 1930**Return value** 1931 1932 | Type | Description | 1933 | ------------------- | ---------------------------- | 1934 | Promise<void> | Promise that returns no value.| 1935 1936**Error codes** 1937 1938For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1939 1940**Example** 1941 1942 ```js 1943 let srcPath = pathDir + "/source.txt"; 1944 let destPath = pathDir + "/dest.txt"; 1945 fs.moveFile(srcPath, destPath, 0).then(() => { 1946 console.info("move file succeed"); 1947 }).catch((err) => { 1948 console.info("move file failed with error message: " + err.message + ", error code: " + err.code); 1949 }); 1950 ``` 1951 1952## fs.moveFile 1953 1954moveFile(src: string, dest: string, mode?: number, callback: AsyncCallback\<void>): void 1955 1956Moves a file. This API uses an asynchronous callback to return the result. 1957 1958**System capability**: SystemCapability.FileManagement.File.FileIO 1959 1960**Parameters** 1961 1962 | Name | Type | Mandatory | Description | 1963 | ------ | ------ | ---- | --------------------------- | 1964 | src | string | Yes | Application sandbox path of the source file.| 1965 | dest | string | Yes | Application sandbox path of the destination file.| 1966 | mode | number | No | Whether to overwrite the file with the same name in the destination directory.<br> The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception.<br> The default value is **0**.| 1967 | callback | AsyncCallback<void> | Yes | Callback invoked when the file is moved. | 1968 1969**Error codes** 1970 1971For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1972 1973**Example** 1974 1975 ```js 1976 let srcPath = pathDir + "/source.txt"; 1977 let destPath = pathDir + "/dest.txt"; 1978 fs.moveFile(srcPath, destPath, 0, (err) => { 1979 if (err) { 1980 console.info("move file failed with error message: " + err.message + ", error code: " + err.code); 1981 } else { 1982 console.info("move file succeed"); 1983 } 1984 }); 1985 ``` 1986 1987## fs.moveFileSync 1988 1989moveFile(src: string, dest: string, mode?: number): void 1990 1991Moves a file synchronously. 1992 1993**System capability**: SystemCapability.FileManagement.File.FileIO 1994 1995**Parameters** 1996 1997 | Name | Type | Mandatory | Description | 1998 | ------ | ------ | ---- | --------------------------- | 1999 | src | string | Yes | Application sandbox path of the source file.| 2000 | dest | string | Yes | Application sandbox path of the destination file.| 2001 | mode | number | No | Whether to overwrite the file with the same name in the destination directory.<br> The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception.<br> The default value is **0**.| 2002 2003**Error codes** 2004 2005For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2006 2007**Example** 2008 2009 ```js 2010 let srcPath = pathDir + "/source.txt"; 2011 let destPath = pathDir + "/dest.txt"; 2012 fs.moveFileSync(srcPath, destPath, 0); 2013 console.info("move file succeed"); 2014 ``` 2015 2016## fs.mkdtemp 2017 2018mkdtemp(prefix: string): Promise<string> 2019 2020Creates a temporary directory. This API uses a promise to return the result. 2021 2022**System capability**: SystemCapability.FileManagement.File.FileIO 2023 2024**Parameters** 2025 2026 | Name | Type | Mandatory | Description | 2027 | ------ | ------ | ---- | --------------------------- | 2028 | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| 2029 2030**Return value** 2031 2032 | Type | Description | 2033 | --------------------- | ---------- | 2034 | Promise<string> | Promise used to return the unique directory generated.| 2035 2036**Error codes** 2037 2038For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2039 2040**Example** 2041 2042 ```js 2043 fs.mkdtemp(pathDir + "/XXXXXX").then((pathDir) => { 2044 console.info("mkdtemp succeed:" + pathDir); 2045 }).catch((err) => { 2046 console.info("mkdtemp failed with error message: " + err.message + ", error code: " + err.code); 2047 }); 2048 ``` 2049 2050## fs.mkdtemp 2051 2052mkdtemp(prefix: string, callback: AsyncCallback<string>): void 2053 2054Creates a temporary directory. This API uses an asynchronous callback to return the result. 2055 2056**System capability**: SystemCapability.FileManagement.File.FileIO 2057 2058**Parameters** 2059 2060 | Name | Type | Mandatory | Description | 2061 | -------- | --------------------------- | ---- | --------------------------- | 2062 | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| 2063 | callback | AsyncCallback<string> | Yes | Callback invoked when a temporary directory is created asynchronously. | 2064 2065**Error codes** 2066 2067For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2068 2069**Example** 2070 2071 ```js 2072 fs.mkdtemp(pathDir + "/XXXXXX", (err, res) => { 2073 if (err) { 2074 console.info("mkdtemp failed with error message: " + err.message + ", error code: " + err.code); 2075 } else { 2076 console.info("mkdtemp success"); 2077 } 2078 }); 2079 ``` 2080 2081## fs.mkdtempSync 2082 2083mkdtempSync(prefix: string): string 2084 2085Synchronously creates a temporary directory. 2086 2087**System capability**: SystemCapability.FileManagement.File.FileIO 2088 2089**Parameters** 2090 2091 | Name | Type | Mandatory | Description | 2092 | ------ | ------ | ---- | --------------------------- | 2093 | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| 2094 2095**Return value** 2096 2097 | Type | Description | 2098 | ------ | ---------- | 2099 | string | Unique path generated.| 2100 2101**Error codes** 2102 2103For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2104 2105**Example** 2106 2107 ```js 2108 let res = fs.mkdtempSync(pathDir + "/XXXXXX"); 2109 ``` 2110 2111## fs.createStream 2112 2113createStream(path: string, mode: string): Promise<Stream> 2114 2115Creates a stream based on the file path. This API uses a promise to return the result. 2116 2117**System capability**: SystemCapability.FileManagement.File.FileIO 2118 2119**Parameters** 2120 2121| Name| Type | Mandatory| Description | 2122| ------ | ------ | ---- | ------------------------------------------------------------ | 2123| path | string | Yes | Application sandbox path of the file. | 2124| 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).| 2125 2126**Return value** 2127 2128 | Type | Description | 2129 | --------------------------------- | --------- | 2130 | Promise<[Stream](#stream)> | Promise used to return the result.| 2131 2132**Error codes** 2133 2134For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2135 2136**Example** 2137 2138 ```js 2139 let filePath = pathDir + "/test.txt"; 2140 fs.createStream(filePath, "r+").then((stream) => { 2141 console.info("Stream created"); 2142 }).catch((err) => { 2143 console.info("createStream failed with error message: " + err.message + ", error code: " + err.code); 2144 }); 2145 ``` 2146 2147 2148## fs.createStream 2149 2150createStream(path: string, mode: string, callback: AsyncCallback<Stream>): void 2151 2152Creates a stream based on the file path. This API uses an asynchronous callback to return the result. 2153 2154**System capability**: SystemCapability.FileManagement.File.FileIO 2155 2156**Parameters** 2157 2158| Name | Type | Mandatory| Description | 2159| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 2160| path | string | Yes | Application sandbox path of the file. | 2161| 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).| 2162| callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is created asynchronously. | 2163 2164**Error codes** 2165 2166For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2167 2168**Example** 2169 2170 ```js 2171 let filePath = pathDir + "/test.txt"; 2172 fs.createStream(filePath, "r+", (err, stream) => { 2173 if (err) { 2174 console.info("create stream failed with error message: " + err.message + ", error code: " + err.code); 2175 } else { 2176 console.info("create stream success"); 2177 } 2178 }); 2179 ``` 2180 2181## fs.createStreamSync 2182 2183createStreamSync(path: string, mode: string): Stream 2184 2185Synchronously creates a stream based on the file path. 2186 2187**System capability**: SystemCapability.FileManagement.File.FileIO 2188 2189**Parameters** 2190 2191| Name| Type | Mandatory| Description | 2192| ------ | ------ | ---- | ------------------------------------------------------------ | 2193| path | string | Yes | Application sandbox path of the file. | 2194| 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).| 2195 2196**Return value** 2197 2198 | Type | Description | 2199 | ------------------ | --------- | 2200 | [Stream](#stream) | Stream opened.| 2201 2202**Error codes** 2203 2204For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2205 2206**Example** 2207 2208 ```js 2209 let filePath = pathDir + "/test.txt"; 2210 let ss = fs.createStreamSync(filePath, "r+"); 2211 ``` 2212 2213 2214## fs.fdopenStream 2215 2216fdopenStream(fd: number, mode: string): Promise<Stream> 2217 2218Opens a stream based on the file descriptor. This API uses a promise to return the result. 2219 2220**System capability**: SystemCapability.FileManagement.File.FileIO 2221 2222**Parameters** 2223 2224 | Name | Type | Mandatory | Description | 2225 | ---- | ------ | ---- | ---------------------------------------- | 2226 | fd | number | Yes | FD of the file. | 2227 | 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).| 2228 2229**Return value** 2230 2231 | Type | Description | 2232 | --------------------------------- | --------- | 2233 | Promise<[Stream](#stream)> | Promise used to return the result.| 2234 2235**Error codes** 2236 2237For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2238 2239**Example** 2240 2241 ```js 2242 let filePath = pathDir + "/test.txt"; 2243 let file = fs.openSync(filePath); 2244 fs.fdopenStream(file.fd, "r+").then((stream) => { 2245 console.info("Stream opened"); 2246 fs.closeSync(file); 2247 }).catch((err) => { 2248 console.info("openStream failed with error message: " + err.message + ", error code: " + err.code); 2249 }); 2250 ``` 2251 2252## fs.fdopenStream 2253 2254fdopenStream(fd: number, mode: string, callback: AsyncCallback<Stream>): void 2255 2256Opens a stream based on the file descriptor. This API uses an asynchronous callback to return the result. 2257 2258**System capability**: SystemCapability.FileManagement.File.FileIO 2259 2260**Parameters** 2261 2262 | Name | Type | Mandatory | Description | 2263 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2264 | fd | number | Yes | FD of the file. | 2265 | 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).| 2266 | callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is opened. | 2267 2268**Error codes** 2269 2270For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2271 2272**Example** 2273 2274 ```js 2275 let filePath = pathDir + "/test.txt"; 2276 let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); 2277 fs.fdopenStream(file.fd, "r+", (err, stream) => { 2278 if (err) { 2279 console.info("fdopen stream failed with error message: " + err.message + ", error code: " + err.code); 2280 } else { 2281 console.info("fdopen stream success"); 2282 fs.closeSync(file); 2283 } 2284 }); 2285 ``` 2286 2287## fs.fdopenStreamSync 2288 2289fdopenStreamSync(fd: number, mode: string): Stream 2290 2291Synchronously opens a stream based on the file descriptor. 2292 2293**System capability**: SystemCapability.FileManagement.File.FileIO 2294 2295**Parameters** 2296 2297 | Name | Type | Mandatory | Description | 2298 | ---- | ------ | ---- | ---------------------------------------- | 2299 | fd | number | Yes | FD of the file. | 2300 | 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).| 2301 2302**Return value** 2303 2304 | Type | Description | 2305 | ------------------ | --------- | 2306 | [Stream](#stream) | Stream opened.| 2307 2308**Error codes** 2309 2310For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2311 2312**Example** 2313 2314 ```js 2315 let filePath = pathDir + "/test.txt"; 2316 let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE); 2317 let ss = fs.fdopenStreamSync(file.fd, "r+"); 2318 fs.closeSync(file); 2319 ``` 2320 2321## Stat 2322 2323Represents detailed file information. Before calling any API of the **Stat()** class, use [stat()](#fsstat) to create a **Stat** instance synchronously or asynchronously. 2324 2325**System capability**: SystemCapability.FileManagement.File.FileIO 2326 2327### Attributes 2328 2329| Name | Type | Readable | Writable | Description | 2330| ------ | ------ | ---- | ---- | ---------------------------------------- | 2331| ino | number | Yes | No | File ID. Different files on the same device have different **ino**s.| | 2332| 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.| 2333| uid | number | Yes | No | ID of the file owner.| 2334| gid | number | Yes | No | ID of the user group of the file.| 2335| size | number | Yes | No | File size, in bytes. This parameter is valid only for regular files. | 2336| 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. | 2337| 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. | 2338| 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. | 2339 2340### isBlockDevice 2341 2342isBlockDevice(): boolean 2343 2344Checks whether this file is a block special file. A block special file supports access by block only, and it is cached when accessed. 2345 2346**System capability**: SystemCapability.FileManagement.File.FileIO 2347 2348**Return value** 2349 2350 | Type | Description | 2351 | ------- | ---------------- | 2352 | boolean | Whether the file is a block special file.| 2353 2354**Error codes** 2355 2356For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2357 2358**Example** 2359 2360 ```js 2361 let filePath = pathDir + "/test.txt"; 2362 let isBLockDevice = fs.statSync(filePath).isBlockDevice(); 2363 ``` 2364 2365### isCharacterDevice 2366 2367isCharacterDevice(): boolean 2368 2369Checks whether this file is a character special file. A character special file supports random access, and it is not cached when accessed. 2370 2371**System capability**: SystemCapability.FileManagement.File.FileIO 2372 2373**Return value** 2374 2375 | Type | Description | 2376 | ------- | ----------------- | 2377 | boolean | Whether the file is a character special file.| 2378 2379**Error codes** 2380 2381For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2382 2383**Example** 2384 2385 ```js 2386 let filePath = pathDir + "/test.txt"; 2387 let isCharacterDevice = fs.statSync(filePath).isCharacterDevice(); 2388 ``` 2389 2390### isDirectory 2391 2392isDirectory(): boolean 2393 2394Checks whether this file is a directory. 2395 2396**System capability**: SystemCapability.FileManagement.File.FileIO 2397 2398**Return value** 2399 2400 | Type | Description | 2401 | ------- | ------------- | 2402 | boolean | Whether the file is a directory.| 2403 2404**Error codes** 2405 2406For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2407 2408**Example** 2409 2410 ```js 2411 let dirPath = pathDir + "/test"; 2412 let isDirectory = fs.statSync(dirPath).isDirectory(); 2413 ``` 2414 2415### isFIFO 2416 2417isFIFO(): boolean 2418 2419Checks whether this file is a named pipe (or FIFO). Named pipes are used for inter-process communication. 2420 2421**System capability**: SystemCapability.FileManagement.File.FileIO 2422 2423**Return value** 2424 2425 | Type | Description | 2426 | ------- | --------------------- | 2427 | boolean | Whether the file is a FIFO.| 2428 2429**Error codes** 2430 2431For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2432 2433**Example** 2434 2435 ```js 2436 let filePath = pathDir + "/test.txt"; 2437 let isFIFO = fs.statSync(filePath).isFIFO(); 2438 ``` 2439 2440### isFile 2441 2442isFile(): boolean 2443 2444Checks whether this file is a regular file. 2445 2446**System capability**: SystemCapability.FileManagement.File.FileIO 2447 2448**Return value** 2449 2450 | Type | Description | 2451 | ------- | --------------- | 2452 | boolean | Whether the file is a regular file.| 2453 2454**Error codes** 2455 2456For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2457 2458**Example** 2459 2460 ```js 2461 let filePath = pathDir + "/test.txt"; 2462 let isFile = fs.statSync(filePath).isFile(); 2463 ``` 2464 2465### isSocket 2466 2467isSocket(): boolean 2468 2469Checks whether this file is a socket. 2470 2471**System capability**: SystemCapability.FileManagement.File.FileIO 2472 2473**Return value** 2474 2475 | Type | Description | 2476 | ------- | -------------- | 2477 | boolean | Whether the file is a socket.| 2478 2479**Error codes** 2480 2481For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2482 2483**Example** 2484 2485 ```js 2486 let filePath = pathDir + "/test.txt"; 2487 let isSocket = fs.statSync(filePath).isSocket(); 2488 ``` 2489 2490### isSymbolicLink 2491 2492isSymbolicLink(): boolean 2493 2494Checks whether this file is a symbolic link. 2495 2496**System capability**: SystemCapability.FileManagement.File.FileIO 2497 2498**Return value** 2499 2500 | Type | Description | 2501 | ------- | --------------- | 2502 | boolean | Whether the file is a symbolic link.| 2503 2504**Error codes** 2505 2506For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2507 2508**Example** 2509 2510 ```js 2511 let filePath = pathDir + "/test"; 2512 let isSymbolicLink = fs.statSync(filePath).isSymbolicLink(); 2513 ``` 2514 2515## Stream 2516 2517Provides a stream for file operations. Before calling any API of the **Stream** class, use **createStream()** to create a **Stream** instance synchronously or asynchronously. 2518 2519### close 2520 2521close(): Promise<void> 2522 2523Closes the stream. This API uses a promise to return the result. 2524 2525**System capability**: SystemCapability.FileManagement.File.FileIO 2526 2527**Return value** 2528 2529 | Type | Description | 2530 | ------------------- | ------------- | 2531 | Promise<void> | Promise used to return the stream close result.| 2532 2533**Error codes** 2534 2535For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2536 2537**Example** 2538 2539 ```js 2540 let filePath = pathDir + "/test.txt"; 2541 let ss= fs.createStreamSync(filePath, "r+"); 2542 ss.close().then(() => { 2543 console.info("File stream closed"); 2544 }).catch((err) => { 2545 console.info("close fileStream failed with error message: " + err.message + ", error code: " + err.code); 2546 }); 2547 ``` 2548 2549### close 2550 2551close(callback: AsyncCallback<void>): void 2552 2553Closes the stream. This API uses an asynchronous callback to return the result. 2554 2555**System capability**: SystemCapability.FileManagement.File.FileIO 2556 2557**Parameters** 2558 2559 | Name | Type | Mandatory | Description | 2560 | -------- | ------------------------- | ---- | ------------- | 2561 | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the stream is closed.| 2562 2563**Error codes** 2564 2565For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2566 2567**Example** 2568 2569 ```js 2570 let filePath = pathDir + "/test.txt"; 2571 let ss= fs.createStreamSync(filePath, "r+"); 2572 ss.close((err) => { 2573 if (err) { 2574 console.info("close stream failed with error message: " + err.message + ", error code: " + err.code); 2575 } else { 2576 console.info("close stream success"); 2577 } 2578 }); 2579 ``` 2580 2581### closeSync 2582 2583closeSync(): void 2584 2585Synchronously closes the stream. 2586 2587**System capability**: SystemCapability.FileManagement.File.FileIO 2588 2589**Error codes** 2590 2591For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2592 2593**Example** 2594 2595 ```js 2596 let filePath = pathDir + "/test.txt"; 2597 let ss= fs.createStreamSync(filePath, "r+"); 2598 ss.closeSync(); 2599 ``` 2600 2601### flush 2602 2603flush(): Promise<void> 2604 2605Flushes the stream. This API uses a promise to return the result. 2606 2607**System capability**: SystemCapability.FileManagement.File.FileIO 2608 2609**Return value** 2610 2611 | Type | Description | 2612 | ------------------- | ------------- | 2613 | Promise<void> | Promise used to return the stream flushing result.| 2614 2615**Error codes** 2616 2617For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2618 2619**Example** 2620 2621 ```js 2622 let filePath = pathDir + "/test.txt"; 2623 let ss= fs.createStreamSync(filePath, "r+"); 2624 ss.flush().then(() => { 2625 console.info("Stream flushed"); 2626 }).catch((err) => { 2627 console.info("flush failed with error message: " + err.message + ", error code: " + err.code); 2628 }); 2629 ``` 2630 2631### flush 2632 2633flush(callback: AsyncCallback<void>): void 2634 2635Flushes the stream. This API uses an asynchronous callback to return the result. 2636 2637**System capability**: SystemCapability.FileManagement.File.FileIO 2638 2639**Parameters** 2640 2641 | Name | Type | Mandatory | Description | 2642 | -------- | ------------------------- | ---- | -------------- | 2643 | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is asynchronously flushed.| 2644 2645**Error codes** 2646 2647For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2648 2649**Example** 2650 2651 ```js 2652 let filePath = pathDir + "/test.txt"; 2653 let ss= fs.createStreamSync(filePath, "r+"); 2654 ss.flush((err) => { 2655 if (err) { 2656 console.info("flush stream failed with error message: " + err.message + ", error code: " + err.code); 2657 } else { 2658 console.info("flush success"); 2659 } 2660 }); 2661 ``` 2662 2663### flushSync 2664 2665flushSync(): void 2666 2667Synchronously flushes the stream. 2668 2669**System capability**: SystemCapability.FileManagement.File.FileIO 2670 2671**Error codes** 2672 2673For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2674 2675**Example** 2676 2677 ```js 2678 let filePath = pathDir + "/test.txt"; 2679 let ss= fs.createStreamSync(filePath, "r+"); 2680 ss.flushSync(); 2681 ``` 2682 2683### write 2684 2685write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): Promise<number> 2686 2687Writes data into the stream. This API uses a promise to return the result. 2688 2689**System capability**: SystemCapability.FileManagement.File.FileIO 2690 2691**Parameters** 2692 2693 | Name | Type | Mandatory | Description | 2694 | ------- | ------------------------------- | ---- | ---------------------------------------- | 2695 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 2696 | 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.| 2697 2698**Return value** 2699 2700 | Type | Description | 2701 | --------------------- | -------- | 2702 | Promise<number> | Promise used to return the length of the data written.| 2703 2704**Error codes** 2705 2706For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2707 2708**Example** 2709 2710 ```js 2711 let filePath = pathDir + "/test.txt"; 2712 let ss= fs.createStreamSync(filePath, "r+"); 2713 ss.write("hello, world",{ offset: 5, length: 5, encoding: 'utf-8' }).then((number) => { 2714 console.info("write succeed and size is:" + number); 2715 }).catch((err) => { 2716 console.info("write failed with error message: " + err.message + ", error code: " + err.code); 2717 }); 2718 ``` 2719 2720### write 2721 2722write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback<number>): void 2723 2724Writes data into the stream. This API uses an asynchronous callback to return the result. 2725 2726**System capability**: SystemCapability.FileManagement.File.FileIO 2727 2728**Parameters** 2729 2730 | Name | Type | Mandatory| Description | 2731 | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | 2732 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 2733 | 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.| 2734 | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | 2735 2736**Error codes** 2737 2738For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2739 2740**Example** 2741 2742 ```js 2743 let filePath = pathDir + "/test.txt"; 2744 let ss= fs.createStreamSync(filePath, "r+"); 2745 ss.write("hello, world", { offset: 5, length: 5, encoding :'utf-8'}, (err, bytesWritten) => { 2746 if (err) { 2747 console.info("write stream failed with error message: " + err.message + ", error code: " + err.code); 2748 } else { 2749 if (bytesWritten) { 2750 console.info("write succeed and size is:" + bytesWritten); 2751 } 2752 } 2753 }); 2754 ``` 2755 2756### writeSync 2757 2758writeSync(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): number 2759 2760Synchronously writes data into the stream. 2761 2762**System capability**: SystemCapability.FileManagement.File.FileIO 2763 2764**Parameters** 2765 2766 | Name | Type | Mandatory | Description | 2767 | ------- | ------------------------------- | ---- | ---------------------------------------- | 2768 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 2769 | 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.| 2770 2771**Return value** 2772 2773 | Type | Description | 2774 | ------ | -------- | 2775 | number | Length of the data written in the file.| 2776 2777**Error codes** 2778 2779For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2780 2781**Example** 2782 2783 ```js 2784 let filePath = pathDir + "/test.txt"; 2785 let ss= fs.createStreamSync(filePath,"r+"); 2786 let num = ss.writeSync("hello, world", {offset: 5, length: 5, encoding :'utf-8'}); 2787 ``` 2788 2789### read 2790 2791read(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): Promise<number> 2792 2793Reads data from the stream. This API uses a promise to return the result. 2794 2795**System capability**: SystemCapability.FileManagement.File.FileIO 2796 2797**Parameters** 2798 2799 | Name | Type | Mandatory | Description | 2800 | ------- | ----------- | ---- | ---------------------------------------- | 2801 | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | 2802 | 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.| 2803 2804**Return value** 2805 2806 | Type | Description | 2807 | ---------------------------------- | ------ | 2808 | Promise<number> | Promise used to return the data read.| 2809 2810**Error codes** 2811 2812For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2813 2814**Example** 2815 2816 ```js 2817 let filePath = pathDir + "/test.txt"; 2818 let ss = fs.createStreamSync(filePath, "r+"); 2819 let buf = new ArrayBuffer(4096); 2820 ss.read(buf, {offset: 5, length: 5}).then((readLen) => { 2821 console.info("Read data successfully"); 2822 console.log(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))); 2823 }).catch((err) => { 2824 console.info("read data failed with error message: " + err.message + ", error code: " + err.code); 2825 }); 2826 ``` 2827 2828### read 2829 2830read(buffer: ArrayBuffer, options?: { position?: number; offset?: number; length?: number; }, callback: AsyncCallback<number>): void 2831 2832Reads data from the stream. This API uses an asynchronous callback to return the result. 2833 2834**System capability**: SystemCapability.FileManagement.File.FileIO 2835 2836**Parameters** 2837 2838 | Name | Type | Mandatory | Description | 2839 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2840 | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | 2841 | 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.| 2842 | callback | AsyncCallback<number> | Yes | Callback invoked when data is read asynchronously from the stream. | 2843 2844**Error codes** 2845 2846For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2847 2848**Example** 2849 2850 ```js 2851 let filePath = pathDir + "/test.txt"; 2852 let ss = fs.createStreamSync(filePath, "r+"); 2853 let buf = new ArrayBuffer(4096) 2854 ss.read(buf, {offset: 5, length: 5}, (err, readLen) => { 2855 if (err) { 2856 console.info("read stream failed with error message: " + err.message + ", error code: " + err.code); 2857 } else { 2858 console.info("Read data successfully"); 2859 console.log(String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))); 2860 } 2861 }); 2862 ``` 2863 2864### readSync 2865 2866readSync(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number 2867 2868Synchronously reads data from the stream. 2869 2870**System capability**: SystemCapability.FileManagement.File.FileIO 2871 2872**Parameters** 2873 2874 | Name | Type | Mandatory | Description | 2875 | ------- | ----------- | ---- | ---------------------------------------- | 2876 | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | 2877 | 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> | 2878 2879**Return value** 2880 2881 | Type | Description | 2882 | ------ | -------- | 2883 | number | Length of the data read.| 2884 2885**Error codes** 2886 2887For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2888 2889**Example** 2890 2891 ```js 2892 let filePath = pathDir + "/test.txt"; 2893 let ss = fs.createStreamSync(filePath, "r+"); 2894 let num = ss.readSync(new ArrayBuffer(4096), {offset: 5, length: 5}); 2895 ``` 2896 2897## File 2898 2899Represents a **File** object opened by **open()**. 2900 2901**System capability**: SystemCapability.FileManagement.File.FileIO 2902 2903### Attributes 2904 2905| Name | Type | Readable | Writable | Description | 2906| ---- | ------ | ---- | ---- | ------- | 2907| fd | number | Yes | No | FD of the file.| 2908 2909### lock 2910 2911lock(exclusive?: boolean): Promise\<void> 2912 2913Applies an exclusive lock or a shared lock on this file in blocking mode. This API uses a promise to return the result. 2914 2915**System capability**: SystemCapability.FileManagement.File.FileIO 2916 2917**Parameters** 2918 2919 | Name | Type | Mandatory | Description | 2920 | ------- | ----------- | ---- | ---------------------------------------- | 2921 | exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | 2922 2923**Return value** 2924 2925 | Type | Description | 2926 | ---------------------------------- | ------ | 2927 | Promise<void> | Promise that returns no value.| 2928 2929**Error codes** 2930 2931For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2932 2933**Example** 2934 2935 ```js 2936 let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 2937 file.lock(true).then(() => { 2938 console.log("lock file successful"); 2939 }).catch((err) => { 2940 console.info("lock file failed with error message: " + err.message + ", error code: " + err.code); 2941 }); 2942 ``` 2943 2944### lock 2945 2946lock(exclusive?: boolean, callback: AsyncCallback\<void>): void 2947 2948Applies an exclusive lock or a shared lock on this file in blocking mode. This API uses a promise to return the result. 2949 2950**System capability**: SystemCapability.FileManagement.File.FileIO 2951 2952**Parameters** 2953 2954 | Name | Type | Mandatory | Description | 2955 | ------- | ----------- | ---- | ---------------------------------------- | 2956 | exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | 2957 | callback | AsyncCallback<void> | Yes | Callback invoked when the file is locked. | 2958 2959**Error codes** 2960 2961For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2962 2963**Example** 2964 2965 ```js 2966 let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 2967 file.lock(true, (err) => { 2968 if (err) { 2969 console.info("lock file failed with error message: " + err.message + ", error code: " + err.code); 2970 } else { 2971 console.log("lock file successful"); 2972 } 2973 }); 2974 ``` 2975 2976### tryLock 2977 2978tryLock(exclusive?: boolean): void 2979 2980Applies an exclusive lock or a shared lock on this file in non-blocking mode. 2981 2982**System capability**: SystemCapability.FileManagement.File.FileIO 2983 2984**Parameters** 2985 2986 | Name | Type | Mandatory | Description | 2987 | ------- | ----------- | ---- | ---------------------------------------- | 2988 | exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | 2989 2990**Error codes** 2991 2992For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2993 2994**Example** 2995 2996 ```js 2997 let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 2998 file.tryLock(true); 2999 console.log("lock file successful"); 3000 ``` 3001 3002### unlock 3003 3004unlock(): void 3005 3006Unlocks this file synchronously. 3007 3008**System capability**: SystemCapability.FileManagement.File.FileIO 3009 3010**Error codes** 3011 3012For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3013 3014**Example** 3015 3016 ```js 3017 let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 3018 file.tryLock(true); 3019 file.unlock(); 3020 console.log("unlock file successful"); 3021 ``` 3022 3023## OpenMode 3024 3025Defines the constants of the **mode** parameter used in **open()**. It specifies the mode for opening a file. 3026 3027**System capability**: SystemCapability.FileManagement.File.FileIO 3028 3029| Name | Type | Value | Description | 3030| ---- | ------ |---- | ------- | 3031| READ_ONLY | number | 0o0 | Open the file in read-only mode.| 3032| WRITE_ONLY | number | 0o1 | Open the file in write-only mode.| 3033| READ_WRITE | number | 0o2 | Open the file in read/write mode.| 3034| CREATE | number | 0o100 | Create a file if the specified file does not exist.| 3035| TRUNC | number | 0o1000 | If the file exists and is open in write-only or read/write mode, truncate the file length to 0.| 3036| APPEND | number | 0o2000 | Open the file in append mode. New data will be written to the end of the file.| 3037| 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.| 3038| DIR | number | 0o200000 | If **path** does not point to a directory, throw an exception.| 3039| NOFOLLOW | number | 0o400000 | If **path** points to a symbolic link, throw an exception.| 3040| SYNC | number | 0o4010000 | Open the file in synchronous I/O mode.| 3041 3042## Filter 3043 3044**System capability**: SystemCapability.FileManagement.File.FileIO 3045 3046Defines the file filtering configuration, which can be used by **listFile()**. 3047 3048| Name | Type | Description | 3049| ----------- | --------------- | ------------------ | 3050| suffix | Array<string> | Locate files that fully match the specified file name extensions, which are of the OR relationship. | 3051| displayName | Array<string> | Locate files that fuzzy match the specified file names, which are of the OR relationship.| 3052| mimeType | Array<string> | Locate files that fully match the specified MIME types, which are of the OR relationship. | 3053| fileSizeOver | number | Locate files that are greater than or equal to the specified size. | 3054| lastModifiedAfter | number | Locate files whose last modification time is the same or later than the specified time. | 3055| excludeMedia | boolean | Whether to exclude the files already in **Media**. | 3056