diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index b1b7419a32599978dfb561452d56a139df835919..15041298fa9ae42688243622b2267ed7a0d9e017 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -215,9 +215,13 @@ - data/rdb - [resultSet](js-apis-data-resultset.md) - File Management - - [@ohos.environment (Environment)](js-apis-environment.md) + - [@ohos.file.environment (Directory Environment Capability)](js-apis-file-environment.md) - [@ohos.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md) - [@ohos.file.fileExtensionInfo (User File Extension Information)](js-apis-fileExtensionInfo.md) + - [@ohos.file.fs (File Management)](js-apis-file-fs.md) + - [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md) + - [@ohos.file.securityLabel (Data Label)](js-apis-file-securityLabel.md) + - [@ohos.file.statvfs (File System Space Statistics)](js-apis-file-statvfs.md) - [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md) - [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md) - [@ohos.storageStatistics (Application Storage Statistics)](js-apis-storage-statistics.md) diff --git a/en/application-dev/reference/apis/js-apis-environment.md b/en/application-dev/reference/apis/js-apis-file-environment.md similarity index 65% rename from en/application-dev/reference/apis/js-apis-environment.md rename to en/application-dev/reference/apis/js-apis-file-environment.md index 3f879c77b9ef5cc9427ff5ac74b5758769ddb70f..9c340eef3974ed2875f417c71cb8a5f7dd4b10d8 100644 --- a/en/application-dev/reference/apis/js-apis-environment.md +++ b/en/application-dev/reference/apis/js-apis-file-environment.md @@ -1,16 +1,17 @@ -# Environment +# @ohos.file.environment (Directory Environment Capability) The **Environment** module provides APIs for obtaining the root directories of the storage and public files. > **NOTE** > -> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - 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. > - The APIs of this module are system APIs and cannot be called by third-party applications. +> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). ## Modules to Import ```js -import environment from '@ohos.environment'; +import environment from '@ohos.file.environment'; ``` ## environment.getStorageDataDir @@ -30,10 +31,10 @@ Obtains the root directory of the storage. This API uses a promise to return the **Example** ```js - environment.getStorageDataDir().then(function(path){ - console.info("getStorageDataDir successfully:"+ path); - }).catch(function(error){ - console.info("getStorageDataDir failed with error:"+ error); + environment.getStorageDataDir().then((path) => { + console.info("getStorageDataDir successfully, Path: " + path); + }).catch((err) => { + console.info("getStorageDataDir failed with error message: " + err.message + ", error code: " + err.code); }); ``` @@ -54,8 +55,12 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac **Example** ```js - environment.getStorageDataDir(function(error, path){ - // do something + environment.getStorageDataDir((err, path) => { + if (err) { + console.info("getStorageDataDir failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("getStorageDataDir successfully, Path: " + path); + } }); ``` @@ -76,10 +81,10 @@ Obtains the root directory of public files. This API uses a promise to return th **Example** ```js - environment.getUserDataDir().then(function(path){ - console.info("getUserDataDir successfully:"+ path); - }).catch(function(error){ - console.info("getUserDataDir failed with error:"+ error); + environment.getUserDataDir().then((path) => { + console.info("getUserDataDir successfully, Path: " + path); + }).catch((err) => { + console.info("getUserDataDir failed with error message: " + err.message + ", error code: " + err.code); }); ``` @@ -100,7 +105,11 @@ Obtains the root directory of public files. This API uses an asynchronous callba **Example** ```js - environment.getUserDataDir(function(error, path){ - // do something + environment.getUserDataDir((err, path) => { + if (err) { + console.info("getUserDataDir failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("getUserDataDir successfully, Path: " + path); + } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-file-fs.md b/en/application-dev/reference/apis/js-apis-file-fs.md new file mode 100644 index 0000000000000000000000000000000000000000..7aef781d4225954cb12c6808ea4d85ad3d2ce4f2 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-file-fs.md @@ -0,0 +1,2374 @@ +# @ohos.file.fs (File Management) + +The **fs** module provides APIs for file operations, including basic file management, directory management, file information statistics, and stream read and write. + +> **NOTE** +> +> - 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. +> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +## Modules to Import + +```js +import fs from '@ohos.file.fs'; +``` + +## Guidelines + +Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the application sandbox as follows: + +**Stage Model** + + ```js +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + let context = this.context; + let pathDir = context.filesDir; + } +} + ``` + +**FA Model** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + + let context = featureAbility.getContext(); + context.getFilesDir().then((data) => { + let pathDir = data; + }) + ``` + +For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context). + +## fs.stat + +stat(file: string|number): Promise<Stat> + +Obtains detailed file information. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file.| + +**Return value** + +| Type | Description | +| ---------------------------- | ---------- | +| Promise<[Stat](#stat)> | Promise used to return the file information obtained.| + +**Example** + + ```js + let filePath = pathDir + "test.txt"; + fs.stat(filePath).then((stat) => { + console.info("get file info succeed, the size of file is " + stat.size); + }).catch((err) => { + console.info("get file info failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## fs.stat + +stat(file: string|number, callback: AsyncCallback<Stat>): void + +Obtains detailed file information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------ | +| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file. | +| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the file information obtained.| + +**Example** + + ```js + fs.stat(pathDir, (err, stat) => { + if (err) { + console.info("get file info failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("get file info succeed, the size of file is " + stat.size); + } + }); + ``` + +## fs.statSync + +statSync(file: string|number): Stat + +Obtains detailed file information synchronously. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file.| + + +**Return value** + +| Type | Description | +| ------------- | ---------- | +| [Stat](#stat) | File information obtained.| + +**Example** + + ```js + let stat = fs.statSync(pathDir); + console.info("get file info succeed, the size of file is " + stat.size); + ``` + +## fs.access + +access(path: string): Promise<boolean> + +Checks whether a file exists. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<boolean> | Promise used to return a Boolean value. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.access(filePath).then((res) => { + if (res) { + console.info("file exists"); + } + }).catch((err) => { + console.info("access failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.access + +access(path: string, callback: AsyncCallback<boolean>): void + +Checks whether a file exists. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.access(filePath, (err, res) => { + if (err) { + console.info("access failed with error message: " + err.message + ", error code: " + err.code); + } else { + if (res) { + console.info("file exists"); + } + } + }); + ``` + +## fs.accessSync + +accessSync(path: string): boolean + +Synchronously checks whether a file exists. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + try { + let res = fs.accessSync(filePath); + if (res) { + console.info("file exists"); + } + } catch(err) { + console.info("accessSync failed with error message: " + err.message + ", error code: " + err.code); + } + ``` + + +## fs.close + +close(file: File|number): Promise<void> + +Closes a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| file | [File](#file)\|number | Yes | File object or FD of the file to close.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.close(file).then(() => { + console.info("File closed"); + fs.closeSync(file); + }).catch((err) => { + console.info("close file failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## fs.close + +close(file: File|number, callback: AsyncCallback<void>): void + +Closes a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------ | +| file | [File](#file)\|number | Yes | File object or FD of the file to close.| +| callback | AsyncCallback<void> | Yes | Callback invoked when the file is closed asynchronously.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.close(file, (err) => { + if (err) { + console.info("close file failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("close file success"); + } + }); + ``` + +## fs.closeSync + +closeSync(file: File|number): void + +Synchronously closes a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| file | [File](#file)\|number | Yes | File object or FD of the file to close.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.closeSync(file); + ``` + +## fs.copyFile + +copyFile(src: string|number, dest: string|number, mode?: number): Promise<void> + +Copies a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | -------------------------- | ---- | ---------------------------------------- | +| src | string\|number | Yes | Path or FD of the file to copy. | +| dest | string\|number | Yes | Destination path of the file or FD of the file created. | +| mode | number | No | Whether to overwrite the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: overwrite the file of the same name.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let srcPath = pathDir + "srcDir/test.txt"; + let dstPath = pathDir + "dstDir/test.txt"; + fs.copyFile(srcPath, dstPath).then(() => { + console.info("copy file succeed"); + }).catch((err) => { + console.info("copy file failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## fs.copyFile + +copyFile(src: string|number, dest: string|number, mode?: number, callback: AsyncCallback<void>): void + +Copies a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------- | ---- | ---------------------------------------- | +| src | string\|number | Yes | Path or FD of the file to copy. | +| dest | string\|number | Yes | Destination path of the file or FD of the file created. | +| mode | number | No | Whether to overwrite the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: overwrite the file with the same name and truncate the part that is not overwritten.| +| callback | AsyncCallback<void> | Yes | Callback invoked when the file is copied asynchronously. | + +**Example** + + ```js + let srcPath = pathDir + "srcDir/test.txt"; + let dstPath = pathDir + "dstDir/test.txt"; + fs.copyFile(srcPath, dstPath, (err) => { + if (err) { + console.info("copy file failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("copy file success"); + } + }); + ``` + + +## fs.copyFileSync + +copyFileSync(src: string|number, dest: string|number, mode?: number): void + +Synchronously copies a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | -------------------------- | ---- | ---------------------------------------- | +| src | string\|number | Yes | Path or FD of the file to copy. | +| dest | string\|number | Yes | Destination path of the file or FD of the file created. | +| mode | number | No | Whether to overwrite the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: overwrite the file with the same name and truncate the part that is not overwritten.| + +**Example** + + ```js + let srcPath = pathDir + "srcDir/test.txt"; + let dstPath = pathDir + "dstDir/test.txt"; + fs.copyFileSync(srcPath, dstPath); + ``` + + +## fs.mkdir + +mkdir(path: string): Promise<void> + +Creates a directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the directory in the application sandbox. | + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let dirPath = pathDir + '/testDir'; + fs.mkdir(dirPath).then(() => { + console.info("Directory created"); + }).catch((err) => { + console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.mkdir + +mkdir(path: string, callback: AsyncCallback<void>): void + +Creates a directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the directory in the application sandbox. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the directory is created asynchronously. | + +**Example** + + ```js + let dirPath = pathDir + '/testDir'; + fs.mkdir(dirPath, (err) => { + if (err) { + console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("mkdir success"); + } + }); + ``` + + +## fs.mkdirSync + +mkdirSync(path: string): void + +Synchronously creates a directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the directory in the application sandbox. | + +**Example** + + ```js + let dirPath = path + '/testDir'; + fs.mkdirSync(dirPath); + ``` + + +## fs.open + +open(path: string, mode?: number): Promise<File> + +Opens a file. This API uses a promise to return the result. File uniform resource identifiers (URIs) are supported. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox or URI of the file. | +| 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.
- **OpenMode.READ_ONLY(0o0)**: Open the file in read-only mode.
- **OpenMode.WRITE_ONLY(0o1)**: Open the file in write-only mode.
- **OpenMode.READ_WRITE(0o2)**: Open the file in read/write mode.
You can also specify the following options, separated by a bitwise OR operator (|). By default, no additional options are given.
- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.
- **OpenMode.TRUNC(0o1000)**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **OpenMode.APPEND(0o2000)**: Open the file in append mode. New data will be added to the end of the file.
- **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.
- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.
- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.
- **OpenMode.SYNC(0o4010000)**: Open the file in synchronous I/O mode.| + +**Return value** + +| Type | Description | +| --------------------- | ----------- | +| Promise<[File](#file)> | Promise used to return the file object.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE).then((file) => { + console.info("file fd: " + file.fd); + }).catch((err) => { + console.info("open file failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.open + +open(path: string, mode?: number, callback: AsyncCallback<File>): void + +Opens a file. This API uses an asynchronous callback to return the result. File URIs are supported. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox or URI of the file. | +| 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.
- **OpenMode.READ_ONLY(0o0)**: Open the file in read-only mode.
- **OpenMode.WRITE_ONLY(0o1)**: Open the file in write-only mode.
- **OpenMode.READ_WRITE(0o2)**: Open the file in read/write mode.
You can also specify the following options, separated by a bitwise OR operator (|). By default, no additional options are given.
- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.
- **OpenMode.TRUNC(0o1000)**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **OpenMode.APPEND(0o2000)**: Open the file in append mode. New data will be added to the end of the file.
- **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.
- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.
- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.
- **OpenMode.SYNC(0o4010000)**: Open the file in synchronous I/O mode.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE, (err, file) => { + if (err) { + console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("file fd: " + file.fd); + } + }); + ``` + +## fs.openSync + +openSync(path: string, mode?: number): File + +Synchronously opens a file. File URIs are supported. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox or URI of the file. | +| 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.
- **OpenMode.READ_ONLY(0o0)**: Open the file in read-only mode.
- **OpenMode.WRITE_ONLY(0o1)**: Open the file in write-only mode.
- **OpenMode.READ_WRITE(0o2)**: Open the file in read/write mode.
You can also specify the following options, separated by a bitwise OR operator (|). By default, no additional options are given.
- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.
- **OpenMode.TRUNC(0o1000)**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **OpenMode.APPEND(0o2000)**: Open the file in append mode. New data will be added to the end of the file.
- **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.
- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.
- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.
- **OpenMode.SYNC(0o4010000)**: Open the file in synchronous I/O mode.| + +**Return value** + +| Type | Description | +| ------ | ----------- | +| [File](#file) | File object opened.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + console.info("file fd: " + file.fd); + fs.closeSync(file); + ``` + +## fs.read + +read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): Promise<number> + +Reads data from a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------- | ---- | ------------------------------------------------------------ | +| fd | number | Yes | FD of the file. | +| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | +| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| + +**Return value** + +| Type | Description | +| ---------------------------------- | ------ | +| Promise<number> | Promise used to return the data read.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); + let buf = new ArrayBuffer(4096); + fs.read(file.fd, buf).then((readLen) => { + console.info("Read file data successfully"); + console.info(String.fromCharCode.apply(null, new Uint8Array(readLen))); + fs.closeSync(file); + }).catch((err) => { + console.info("read file data failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## fs.read + +read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }, callback: AsyncCallback<number>): void + +Reads data from a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | +| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| +| callback | AsyncCallback<number> | Yes | Callback invoked when the data is read asynchronously. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); + let buf = new ArrayBuffer(4096); + fs.read(file.fd, buf, (err, readLen) => { + if (err) { + console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("Read file data successfully"); + console.info(String.fromCharCode.apply(null, new Uint8Array(readLen))); + fs.closeSync(file); + } + }); + ``` + + +## fs.readSync + +readSync(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number + +Synchronously reads data from a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------- | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | +| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Length of the data read.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); + let buf = new ArrayBuffer(4096); + let num = fs.readSync(file.fd, buf); + fs.closeSync(file); + ``` + + +## fs.rmdir + +rmdir(path: string): Promise<void> + +Deletes a directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the directory in the application sandbox.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let dirPath = pathDir + '/testDir'; + fs.rmdir(dirPath).then(() => { + console.info("Directory deleted"); + }).catch((err) => { + console.info("rmdir failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.rmdir + +rmdir(path: string, callback: AsyncCallback<void>): void + +Deletes a directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------- | +| path | string | Yes | Path of the directory in the application sandbox.| +| callback | AsyncCallback<void> | Yes | Callback invoked when the directory is deleted asynchronously. | + +**Example** + + ```js + let dirPath = pathDir + '/testDir'; + fs.rmdir(dirPath, (err) => { + if (err) { + console.info("rmdir failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("Directory deleted"); + } + }); + ``` + + +## fs.rmdirSync + +rmdirSync(path: string): void + +Synchronously deletes a directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the directory in the application sandbox.| + +**Example** + + ```js + let dirPath = pathDir + '/testDir'; + fs.rmdirSync(dirPath); + ``` + + +## fs.unlink + +unlink(path: string): Promise<void> + +Deletes a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the file in the application sandbox.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.unlink(filePath).then(() => { + console.info("File deleted"); + }).catch((err) => { + console.info("remove file failed with error message: " + err.message + ", error code: " + err.codeor); + }); + ``` + + +## fs.unlink + +unlink(path: string, callback: AsyncCallback<void>): void + +Deletes a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------- | +| path | string | Yes | Path of the file in the application sandbox.| +| callback | AsyncCallback<void> | Yes | Callback invoked when the file is deleted asynchronously. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.unlink(filePath, (err) => { + if (err) { + console.info("remove file failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("File deleted"); + } + }); + ``` + + +## fs.unlinkSync + +unlinkSync(path: string): void + +Synchronously deletes a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the file in the application sandbox.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.unlinkSync(filePath); + ``` + + +## fs.write + +write(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): Promise<number> + +Writes data into a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | +| options | Object | No | The options are as follows:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + +**Return value** + +| Type | Description | +| --------------------- | -------- | +| Promise<number> | Promise used to return the length of the data written.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + fs.write(file.fd, "hello, world").then((writeLen) => { + console.info("write data to file succeed and size is:" + writeLen); + fs.closeSync(file); + }).catch((err) => { + console.info("write data to file failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.write + +write(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback<number>): void + +Writes data into a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | +| options | Object | No | The options are as follows:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| +| callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + fs.write(file.fd, "hello, world", (err, writeLen) => { + if (err) { + console.info("write failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("write data to file succeed and size is:" + writeLen); + fs.closeSync(file); + } + }); + ``` + + +## fs.writeSync + +writeSync(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): number + +Synchronously writes data into a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | +| options | Object | No | The options are as follows:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Length of the data written in the file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + let writeLen = fs.writeSync(file.fd, "hello, world"); + console.info("write data to file succeed and size is:" + writeLen); + fs.closeSync(file); + ``` + +## fs.truncate + +truncate(file: string|number, len?: number): Promise<void> + +Truncates a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------- | +| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file. | +| len | number | No | File length, in bytes, after truncation.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let len = 5; + fs.truncate(filePath, len).then(() => { + console.info("File truncated"); + }).catch((err) => { + console.info("truncate file failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.truncate + +truncate(file: string|number, len?: number, callback: AsyncCallback<void>): void + +Truncates a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------- | +| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file. | +| len | number | No | File length, in bytes, after truncation.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let len = 5; + fs.truncate(filePath, len, (err) => { + if (err) { + console.info("truncate failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("truncate success"); + } + }); + ``` + + +## fs.truncateSync + +truncateSync(file: string|number, len?: number): void + +Synchronously truncates a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------- | +| file | string\|number | Yes | Path of the file in the application sandbox or file descriptor (FD) of the file. | +| len | number | No | File length, in bytes, after truncation.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let len = 5; + fs.truncateSync(filePath, len); + ``` + + +## fs.readText + +readText(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }): Promise<string> + +Reads the text content of a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filePath | string | Yes | Path of the file in the application sandbox. | +| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the file length.
- **encoding** (string): format of the string to be encoded. The default value is **'utf-8'**, which is the only value supported.| + +**Return value** + +| Type | Description | +| --------------------- | ---------- | +| Promise<string> | Promise used to return the content read.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.readText(filePath).then((str) => { + console.info("readText succeed:" + str); + }).catch((err) => { + console.info("readText failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.readText + +readText(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback<string>): void + +Reads the text content of a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| filePath | string | Yes | Path of the file in the application sandbox. | +| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the file length.
- **encoding** (string): format of the string to be encoded. The default value is **'utf-8'**, which is the only value supported.| +| callback | AsyncCallback<string> | Yes | Callback used to return the content read. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.readText(filePath, { offset: 1, encoding: 'UTF-8' }, (err, str) => { + if (err) { + console.info("read text failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("readText succeed:" + str); + } + }); + ``` + + +## fs.readTextSync + +readTextSync(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }): string + +Synchronously reads the text of a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filePath | string | Yes | Path of the file in the application sandbox. | +| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the file length.
- **encoding** (string): format of the string to be encoded. The default value is **'utf-8'**, which is the only value supported.| + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| string | Promise used to return the content of the file read.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let str = fs.readTextSync(filePath, {offset: 1, length: 3}); + console.info("readText succeed:" + str); + ``` + +## fs.lstat + +lstat(path: string): Promise<Stat> + +Obtains information about a symbolic link. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| path | string | Yes | Path of the symbolic link in the application sandbox.| + +**Return value** + +| Type | Description | +| ---------------------------- | ---------- | +| Promise<[Stat](#stat)> | Promise used to return the symbolic link information obtained. For details, see **stat**.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.lstat(filePath).then((stat) => { + console.info("get link status succeed, the size of file is" + stat.size); + }).catch((err) => { + console.info("get link status failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.lstat + +lstat(path: string, callback: AsyncCallback<Stat>): void + +Obtains information about a symbolic link. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | -------------------------------------- | +| path | string | Yes | Path of the symbolic link in the application sandbox.| +| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback used to return the symbolic link information obtained. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.lstat(filePath, (err, stat) => { + if (err) { + console.info("lstat failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("get link status succeed, the size of file is" + stat.size); + } + }); + ``` + +## fs.lstatSync + +lstatSync(path: string): Stat + +Obtains information about a symbolic link synchronously. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| path | string | Yes | Path of the file in the application sandbox.| + +**Return value** + +| Type | Description | +| ------------- | ---------- | +| [Stat](#stat) | File information obtained.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let stat = fs.lstatSync(filePath); + ``` + +## fs.rename + +rename(oldPath: string, newPath: string): Promise<void> + +Renames a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------------- | +| oldPath | string | Yes | Path of the file to rename in the application sandbox.| +| newPath | string | Yes | Path of the renamed file in the application sandbox. | + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/new.txt'; + fs.rename(srcFile, dstFile).then(() => { + console.info("File renamed"); + }).catch((err) => { + console.info("rename failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## fs.rename + +rename(oldPath: string, newPath: string, callback: AsyncCallback<void>): void + +Renames a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------- | +| oldPath | string | Yes | Path of the file to rename in the application sandbox.| +| newPath | string | Yes | Path of the renamed file in the application sandbox. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously renamed. | + +**Example** + + ```js + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/new.txt'; + fs.rename(srcFile, dstFile, (err) => { + if (err) { + console.info("rename failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("rename success"); + } + }); + ``` + +## fs.renameSync + +renameSync(oldPath: string, newPath: string): void + +Synchronously renames a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------------- | +| oldPath | string | Yes | Path of the file to rename in the application sandbox.| +| newPath | string | Yes | Path of the renamed file in the application sandbox. | + +**Example** + + ```js + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/new.txt'; + fs.renameSync(srcFile, dstFile); + ``` + + +## fs.fsync + +fsync(fd: number): Promise<void> + +Flushes data of a file to disk. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| fd | number | Yes | FD of the file.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.fsync(file.fd).then(() => { + console.info("Data flushed"); + }).catch((err) => { + console.info("sync data failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.fsync + +fsync(fd: number, callback: AsyncCallback<void>): void + +Flushes data of a file to disk. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | --------------- | +| fd | number | Yes | FD of the file. | +| Callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.fsync(file.fd, (err) => { + if (err) { + console.info("fsync failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("fsync success"); + fs.closeSync(file); + } + }); + ``` + + +## fs.fsyncSync + +fsyncSync(fd: number): void + +Flushes data of a file to disk in synchronous mode. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| fd | number | Yes | FD of the file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.fsyncSync(file.fd); + fs.closeSync(file); + ``` + + +## fs.fdatasync + +fdatasync(fd: number): Promise<void> + +Flushes data of a file to disk. This API uses a promise to return the result. **fdatasync()** is similar to **fsync()**, but does not flush modified metadata unless that metadata is needed. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| fd | number | Yes | FD of the file.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.fdatasync(file.fd).then((err) => { + console.info("Data flushed"); + fs.closeSync(file); + }).catch((err) => { + console.info("sync data failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.fdatasync + +fdatasync(fd: number, callback: AsyncCallback<void>): void + +Flushes data of a file to disk. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ----------------- | +| fd | number | Yes | FD of the file. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.fdatasync (file.fd, (err) => { + if (err) { + console.info("fdatasync failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("fdatasync success"); + fs.closeSync(file); + } + }); + ``` + +## fs.fdatasyncSync + +fdatasyncSync(fd: number): void + +Synchronizes data in a file in synchronous mode. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| fd | number | Yes | FD of the file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + let stat = fs.fdatasyncSync(file.fd); + fs.closeSync(file); + ``` + + +## fs.symlink + +symlink(target: string, srcPath: string): Promise<void> + +Creates a symbolic link based on a file path. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------------- | +| target | string | Yes | Path of the source file in the application sandbox. | +| srcPath | string | Yes | Path of the symbolic link in the application sandbox.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/test'; + fs.symlink(srcFile, dstFile).then(() => { + console.info("Symbolic link created"); + }).catch((err) => { + console.info("symlink failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.symlink +symlink(target: string, srcPath: string, callback: AsyncCallback<void>): void + +Creates a symbolic link based on a file path. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------- | +| target | string | Yes | Path of the source file in the application sandbox. | +| srcPath | string | Yes | Path of the symbolic link in the application sandbox. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the symbolic link is created asynchronously.| + +**Example** + + ```js + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/test'; + fs.symlink(srcFile, dstFile, (err) => { + if (err) { + console.info("symlink failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("symlink success"); + } + }); + ``` + +## fs.symlinkSync + +symlinkSync(target: string, srcPath: string): void + +Synchronously creates a symbolic link based on a file path. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------------- | +| target | string | Yes | Path of the source file in the application sandbox. | +| srcPath | string | Yes | Path of the symbolic link in the application sandbox.| + +**Example** + + ```js + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/test'; + fs.symlinkSync(srcFile, dstFile); + ``` + +## fs.mkdtemp + +mkdtemp(prefix: string): Promise<string> + +Creates a temporary directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------------------- | +| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + +**Return value** + +| Type | Description | +| --------------------- | ---------- | +| Promise<string> | Promise used to return the unique directory generated.| + +**Example** + + ```js + fs.mkdtemp(pathDir + "/XXXXXX").then((pathDir) => { + console.info("mkdtemp succeed:" + pathDir); + }).catch((err) => { + console.info("mkdtemp failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.mkdtemp + +mkdtemp(prefix: string, callback: AsyncCallback<string>): void + +Creates a temporary directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------------------- | +| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| +| callback | AsyncCallback<string> | Yes | Callback invoked when a temporary directory is created asynchronously. | + +**Example** + + ```js + fs.mkdtemp(pathDir + "/XXXXXX", (err, res) => { + if (err) { + console.info("mkdtemp failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("mkdtemp success"); + } + }); + ``` + +## fs.mkdtempSync + +mkdtempSync(prefix: string): string + +Synchronously creates a temporary directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------------------- | +| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + +**Return value** + +| Type | Description | +| ------ | ---------- | +| string | Unique path generated.| + +**Example** + + ```js + let res = fs.mkdtempSync(pathDir + "/XXXXXX"); + ``` + +## fs.createStream + +createStream(path: string, mode: string): Promise<Stream> + +Opens a file stream based on the file path. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | +| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **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.
- **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).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + +**Return value** + +| Type | Description | +| --------------------------------- | --------- | +| Promise<[Stream](#stream)> | Promise used to return the result.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.createStream(filePath, "r+").then((stream) => { + console.info("Stream created"); + }).catch((err) => { + console.info("createStream failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.createStream + +createStream(path: string, mode: string, callback: AsyncCallback<Stream>): void + +Opens a file stream based on the file path. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | +| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **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.
- **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).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| +| callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + fs.createStream(filePath, "r+", (err, stream) => { + if (err) { + console.info("create stream failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("create stream success"); + } + }); + ``` + +## fs.createStreamSync + +createStreamSync(path: string, mode: string): Stream + +Synchronously opens a stream based on the file path. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | +| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **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.
- **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).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + +**Return value** + +| Type | Description | +| ------------------ | --------- | +| [Stream](#stream) | Stream opened.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss = fs.createStreamSync(filePath, "r+"); + ``` + + +## fs.fdopenStream + +fdopenStream(fd: number, mode: string): Promise<Stream> + +Opens a file stream based on the file descriptor. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **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.
- **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).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + +**Return value** + +| Type | Description | +| --------------------------------- | --------- | +| Promise<[Stream](#stream)> | Promise used to return the result.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath); + fs.fdopenStream(file.fd, "r+").then((stream) => { + console.info("Stream opened"); + fs.closeSync(file); + }).catch((err) => { + console.info("openStream failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +## fs.fdopenStream + +fdopenStream(fd: number, mode: string, callback: AsyncCallback<Stream>): void + +Opens a file stream based on the file descriptor. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **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.
- **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).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| +| callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); + fs.fdopenStream(file.fd, "r+", (err, stream) => { + if (err) { + console.info("fdopen stream failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("fdopen stream success"); + fs.closeSync(file); + } + }); + ``` + +## fs.fdopenStreamSync + +fdopenStreamSync(fd: number, mode: string): Stream + +Synchronously opens a stream based on the file descriptor. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| fd | number | Yes | FD of the file. | +| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **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.
- **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).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + +**Return value** + +| Type | Description | +| ------------------ | --------- | +| [Stream](#stream) | Stream opened.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE); + let ss = fs.fdopenStreamSync(file.fd, "r+"); + fs.closeSync(file); + ``` + +## Stat + +Represents detailed file information. Before calling any API of the **Stat()** class, use [stat()](#fsstat) to create a **Stat** instance synchronously or asynchronously. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +### Attributes + +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | ---------------------------------------- | +| ino | number | Yes | No | File ID. Different files on the same device have different **ino**s.| | +| mode | number | Yes | No | File permissions. The meaning of each bit is as follows:
- **0o400**: The owner has the read permission on a regular file or a directory entry.
- **0o200**: The owner has the permission to write a regular file or create and delete a directory entry.
- **0o100**: The owner has the permission to execute a regular file or search for the specified path in a directory.
- **0o040**: The user group has the read permission on a regular file or a directory entry.
- **0o020**: The user group has the permission to write a regular file or create and delete a directory entry.
- **0o010**: The user group has the permission to execute a regular file or search for the specified path in a directory.
- **0o004**: Other users have the permission to read a regular file or read a directory entry.
- **0o002**: Other users have the permission to write a regular file or create and delete a directory entry.
- **0o001**: Other users have the permission to execute a regular file or search for the specified path in a directory.| +| uid | number | Yes | No | ID of the file owner.| +| gid | number | Yes | No | ID of the user group of the file.| +| size | number | Yes | No | File size, in bytes. This parameter is valid only for regular files. | +| atime | number | Yes | No | Time of the last access to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | +| mtime | number | Yes | No | Time of the last modification to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | +| ctime | number | Yes | No | Time of the last status change of the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | + + +### isBlockDevice + +isBlockDevice(): boolean + +Checks whether this file is a block special file. A block special file supports access by block only, and it is cached when accessed. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | ---------------- | +| boolean | Whether the file is a block special file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let isBLockDevice = fs.statSync(filePath).isBlockDevice(); + ``` + +### isCharacterDevice + +isCharacterDevice(): boolean + +Checks whether this file is a character special file. A character special file supports random access, and it is not cached when accessed. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | ----------------- | +| boolean | Whether the file is a character special file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let isCharacterDevice = fs.statSync(filePath).isCharacterDevice(); + ``` + + +### isDirectory + +isDirectory(): boolean + +Checks whether this file is a directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | ------------- | +| boolean | Whether the file is a directory.| + +**Example** + + ```js + let dirPath = pathDir + "/test"; + let isDirectory = fs.statSync(dirPath).isDirectory(); + ``` + + +### isFIFO + +isFIFO(): boolean + +Checks whether this file is a named pipe (or FIFO). Named pipes are used for inter-process communication. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | --------------------- | +| boolean | Whether the file is a FIFO.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let isFIFO = fs.statSync(filePath).isFIFO(); + ``` + + +### isFile + +isFile(): boolean + +Checks whether this file is a regular file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | --------------- | +| boolean | Whether the file is a regular file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let isFile = fs.statSync(filePath).isFile(); + ``` + + +### isSocket + +isSocket(): boolean + +Checks whether this file is a socket. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | -------------- | +| boolean | Whether the file is a socket.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let isSocket = fs.statSync(filePath).isSocket(); + ``` + + +### isSymbolicLink + +isSymbolicLink(): boolean + +Checks whether this file is a symbolic link. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------- | --------------- | +| boolean | Whether the file is a symbolic link.| + +**Example** + + ```js + let filePath = pathDir + "/test"; + let isSymbolicLink = fs.statSync(filePath).isSymbolicLink(); + ``` + +## Stream + +Provides file stream management. Before calling any API of the **Stream** class, use **createStream()** to create a **Stream** instance synchronously or asynchronously. + + +### close + +close(): Promise<void> + +Closes the stream. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<void> | Promise used to return the stream close result.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.close().then(() => { + console.info("File stream closed"); + }).catch((err) => { + console.info("close fileStream failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +### close + +close(callback: AsyncCallback<void>): void + +Closes the stream. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------- | +| callback | AsyncCallback<void> | Yes | Callback invoked when the stream is closed asynchronously.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.close((err) => { + if (err) { + console.info("close stream failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("close stream success"): + } + }); + ``` + +### closeSync + +closeSync(): void + +Synchronously closes the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.closeSync(); + ``` + +### flush + +flush(): Promise<void> + +Flushes the stream. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<void> | Promise used to return the stream flushing result.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.flush().then(() => { + console.info("Stream flushed"); + }).catch((err) => { + console.info("flush failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +### flush + +flush(callback: AsyncCallback<void>): void + +Flushes the stream. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | -------------- | +| callback | AsyncCallback<void> | Yes | Callback invoked when the stream is asynchronously flushed.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.flush((err) => { + if (err) { + console.info("flush stream failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("flush success"); + } + }); + ``` + +### flushSync + +flushSync(): void + +Synchronously flushes the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.flushSync(); + ``` + +### write + +write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): Promise<number> + +Writes data into the stream. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------------------------------------- | +| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | +| options | Object | No | The options are as follows:
- **length** (number): length of the data to write. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + +**Return value** + +| Type | Description | +| --------------------- | -------- | +| Promise<number> | Promise used to return the length of the data written.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.write("hello, world",{ offset: 5, length: 5, encoding: 'utf-8' }).then((number) => { + console.info("write succeed and size is:" + number); + }).catch((err) => { + console.info("write failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +### write + +write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback<number>): void + +Writes data into the stream. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | +| options | Object | No | The options are as follows:
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| +| callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath, "r+"); + ss.write("hello, world", { offset: 5, length: 5, encoding :'utf-8'}, (err, bytesWritten) => { + if (err) { + console.info("write stream failed with error message: " + err.message + ", error code: " + err.code); + } else { + if (bytesWritten) { + console.info("write succeed and size is:" + bytesWritten); + } + } + }); + ``` + +### writeSync + +writeSync(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): number + +Synchronously writes data into the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------------------------------------- | +| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | +| options | Object | No | The options are as follows:
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Length of the data written in the file.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss= fs.createStreamSync(filePath,"r+"); + let num = ss.writeSync("hello, world", {offset: 5, length: 5, encoding :'utf-8'}); + ``` + +### read + +read(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): Promise<number> + +Reads data from the stream. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------- | ---- | ---------------------------------------- | +| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | +| options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. By default, data is read from the current position.| + +**Return value** + +| Type | Description | +| ---------------------------------- | ------ | +| Promise<number> | Promise used to return the data read.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss = fs.createStreamSync(filePath, "r+"); + let buf = new ArrayBuffer(4096); + ss.read(buf, {offset: 5, length: 5}).then((readLen) => { + console.info("Read data successfully"); + console.log(String.fromCharCode.apply(null, new Uint8Array(buf))); + }).catch((err) => { + console.info("read data failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + + +### read + +read(buffer: ArrayBuffer, options?: { position?: number; offset?: number; length?: number; }, callback: AsyncCallback<number>): void + +Reads data from the stream. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | +| options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.| +| callback | AsyncCallback<number> | Yes | Callback invoked when data is read asynchronously from the stream. | + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss = fs.createStreamSync(filePath, "r+"); + let buf = new ArrayBuffer(4096) + ss.read(buf, {offset: 5, length: 5}, (err, readLen) => { + if (err) { + console.info("read stream failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("Read data successfully"); + console.log(String.fromCharCode.apply(null, new Uint8Array(buf))); + } + }); + ``` + +### readSync + +readSync(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number + +Synchronously reads data from the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------- | ---- | ---------------------------------------- | +| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | +| options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
| + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Length of the data read.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + let ss = fs.createStreamSync(filePath, "r+"); + let num = ss.readSync(new ArrayBuffer(4096), {offset: 5, length: 5}); + ``` + +## File + +Represents a **File** object opened by **open()**. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +### Attributes + +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ------- | +| fd | number | Yes | No | FD of the file.| + +## OpenMode + +Defines the constants of the **mode** parameter used in **open()**. It species the mode for opening a file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +| Name | Type | Value | Description | +| ---- | ------ |---- | ------- | +| READ_ONLY | number | 0o0 | Open the file in read-only mode.| +| WRITE_ONLY | number | 0o1 | Open the file in write-only mode.| +| READ_WRITE | number | 0o2 | Open the file in read/write mode.| +| CREATE | number | 0o100 | Create a file if the specified file does not exist.| +| TRUNC | number | 0o1000 | If the file exists and is open in write-only or read/write mode, truncate the file length to 0.| +| APPEND | number | 0o2000 | Open the file in append mode. New data will be written to the end of the file.| +| NONBLOCK | number | 0o4000 | If **path** points to a named pipe (FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.| +| DIR | number | 0o200000 | If **path** does not point to a directory, throw an exception.| +| NOFOLLOW | number | 0o400000 | If **path** points to a symbolic link, throw an exception.| +| SYNC | number | 0o4010000 | Open the file in synchronous I/O mode.| diff --git a/en/application-dev/reference/apis/js-apis-file-hash.md b/en/application-dev/reference/apis/js-apis-file-hash.md new file mode 100644 index 0000000000000000000000000000000000000000..fca5de996e882e8a568dd3851512ed5e8be18c9c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-file-hash.md @@ -0,0 +1,103 @@ +# @ohos.file.hash (File Hash Processing) + +The **fileHash** module implements hash processing on files. + +> **NOTE** +> +> - 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. +> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +## Modules to Import + +```js +import Hash from '@ohos.file.hash'; +``` + +## Guidelines + +Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the file or directory in the application sandbox as follows: + +**Stage Model** + + ```js +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + let context = this.context; + let pathDir = context.filesDir; + } +} + ``` + +**FA Model** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + + let context = featureAbility.getContext(); + context.getFilesDir().then((data) => { + let pathDir = data; + }) + ``` + +For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context). + +## Hash.hash + +hash(path: string, algorithm: string): Promise<string> + +Calculates a hash value for a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | +| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.| + +**Return value** + +| Type | Description | +| --------------------- | -------------------------- | +| Promise<string> | Promise used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.| + +**Example** + + ```js + let filePath = pathDir + "/test.txt"; + Hash.hash(filePath, "sha256").then((str) => { + console.info("calculate file hash succeed:" + str); + }).catch((err) => { + console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## Hash.hash + +hash(path: string, algorithm: string, callback: AsyncCallback<string>): void + +Calculates a hash value for a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the file in the application sandbox. | +| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.| +| callback | AsyncCallback<string> | Yes | Callback used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.| + +**Example** + ```js + Hash.hash(filePath, "sha256", (err, str) => { + if (err) { + console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("calculate file hash succeed:" + str); + } + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-file-securityLabel.md b/en/application-dev/reference/apis/js-apis-file-securityLabel.md new file mode 100644 index 0000000000000000000000000000000000000000..b9071ecc64025491ed21e55490f4753b83440eb1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-file-securityLabel.md @@ -0,0 +1,207 @@ +# @ohos.file.securityLabel (Data Label) + +The **securityLabel** module provides APIs for managing data security levels of files, including obtaining and setting file security levels. + +> **NOTE** +> +> - 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. +>- The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +## Modules to Import + +```js +import securityLabel from '@ohos.file.securityLabel'; +``` + +## Guidelines + +Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the file or directory in the application sandbox as follows: + +**Stage Model** + + ```js +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + let context = this.context; + let pathDir = context.filesDir; + } +} + ``` + +**FA Model** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + + let context = featureAbility.getContext(); + context.getFilesDir().then((data) => { + let pathDir = data; + }) + ``` + +For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context). + +## securityLabel.setSecurityLabel + +setSecurityLabel(path:string, type:dataLevel):Promise<void> + +Sets a security label for a file in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------------------------------- | +| path | string | Yes | Path of the target file. | +| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + securityLabel.setSecurityLabel(path, "s0").then(() => { + console.info("setSecurityLabel successfully"); + }).catch((err) => { + console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## securityLabel.setSecurityLabel + +setSecurityLabel(path:string, type:dataLevel, callback: AsyncCallback<void>):void + +Sets a security label for a file in asynchronous mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | -------------------------------------------- | +| path | string | Yes | Path of the target file. | +| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + + ```js + securityLabel.setSecurityLabel(path, "s0", (err) => { + if (err) { + console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("setSecurityLabel successfully."); + } + }); + ``` + +## securityLabel.setSecurityLabelSync + +setSecurityLabelSync(path:string, type:dataLevel):void + +Sets a security label for a file in synchronous mode. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------------------------------- | +| path | string | Yes | Path of the target file. | +| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| + +**Example** + +```js +securityLabel.setSecurityLabelSync(path, "s0"); +``` + +## securityLabel.getSecurityLabel + +getSecurityLabel(path:string):Promise<string> + +Obtains the security label of a file in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| path | string | Yes | Path of the target file.| + +**Return value** + +| Type | Description | +| --------------------- | ------------ | +| Promise<string> | Security label obtained.| + +**Example** + + ```js + securityLabel.getSecurityLabel(path).then((type) => { + console.log("getSecurityLabel successfully, Label: " + type); + }).catch((err) => { + console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## securityLabel.getSecurityLabel + +getSecurityLabel(path:string, callback:AsyncCallback<string>): void + +Obtains the security label of a file in asynchronous mode. This API uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------- | +| path | string | Yes | Path of the target file. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the security label obtained.| + +**Example** + + ```js + securityLabel.getSecurityLabel(path, (err, type) => { + if (err) { + console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.log("getSecurityLabel successfully, Label: " + type); + } + }); + ``` +## securityLabel.getSecurityLabelSync + +getSecurityLabelSync(path:string):string + +Obtains the security label of a file in synchronous mode. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| path | string | Yes | Path of the target file.| + +**Return value** + +| Type | Description | +| ------ | ------------ | +| string | Security label obtained.| + +**Example** + +```js +let type = securityLabel.getSecurityLabelSync(path); +console.log("getSecurityLabel successfully, Label: " + type); +``` diff --git a/en/application-dev/reference/apis/js-apis-file-statvfs.md b/en/application-dev/reference/apis/js-apis-file-statvfs.md new file mode 100644 index 0000000000000000000000000000000000000000..8241f4734312251f1d4dce13888a2e8ce521ca90 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-file-statvfs.md @@ -0,0 +1,131 @@ +# @ohos.file.statvfs (File System Space Statistics) + +The **statfs** module provides APIs for obtaining file system information, including the total number of bytes and the number of idle bytes of the file system. + +> **NOTE** +> +> - 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. +> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). + +## Modules to Import + +```js +import statvfs from '@ohos.file.statvfs'; +``` +## statvfs.getFreeSize + +getFreeSize(path:string):Promise<number> + +Obtains the number of free bytes of the specified file system in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| + +**Return value** + +| Type | Description | +| --------------------- | -------------- | +| Promise<number> | Promise used to return the number of free bytes obtained.| + +**Example** + + ```js + let path = "/dev"; + statfs.getFreeSize(path).then((number) => { + console.info("getFreeSize promise successfully, Size: " + number); + }).catch((err) => { + console.info("getFreeSize failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## statfs.getFreeSize + +getFreeSize(path:string, callback:AsyncCallback<number>): void + +Obtains the number of free bytes of the specified file system in asynchronous mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of free bytes obtained.| + +**Example** + + ```js + let path = "/dev"; + statfs.getFreeSize(path, (err, number) => { + if (err) { + console.info("getFreeSize failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("getFreeSize callback successfully, Size: " + number); + } + }); + ``` + +## statfs.getTotalSize + +getTotalSize(path: string): Promise<number> + +Obtains the total number of bytes of the specified file system in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| + +**Return value** + +| Type | Description | +| --------------------- | ------------ | +| Promise<number> | Promise used to return the total number of bytes obtained.| + +**Example** + + ```js + let path = "/dev"; + statfs.getTotalSize(path).then((number) => { + console.info("getTotalSize promise successfully, Size: " + number); + }).catch((err) => { + console.info("getTotalSize with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## statfs.getTotalSize + +getTotalSize(path: string, callback: AsyncCallback<number>): void + +Obtains the total number of bytes of the specified file system in asynchronous mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the total number of bytes obtained. | + +**Example** + + ```js + let path = "/dev"; + statfs.getTotalSize(path, (err, number) => { + if (err) { + console.info("getTotalSize with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("getTotalSize promise successfully, Size: " + number); + } + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-statfs.md b/en/application-dev/reference/apis/js-apis-statfs.md index 975ea9f78454ac498ad22986dfa97b15b292f519..9e3d28d465e097d57055339534152f72d53b95fc 100644 --- a/en/application-dev/reference/apis/js-apis-statfs.md +++ b/en/application-dev/reference/apis/js-apis-statfs.md @@ -1,9 +1,12 @@ # @ohos.statfs (statfs) -The statfs module provides APIs for obtaining file system information, including the total number of bytes and the number of idle bytes of the file system. +The **statfs** module provides APIs for obtaining file system information, including the total number of bytes and the number of idle bytes of the file system. -> **NOTE**
-> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - The APIs provided by this module are deprecated since API version 9. You are advised to use [@ohos.file.statvfs](js-apis-file-statvfs.md). ## Modules to Import @@ -20,15 +23,15 @@ Obtains the number of free bytes of the specified file system in asynchronous mo **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ---------------------------- | - | path | string | Yes | File path of the file system.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| **Return value** - | Type | Description | - | --------------------- | -------------- | - | Promise<number> | Promise used to return the number of free bytes obtained.| +| Type | Description | +| --------------------- | -------------- | +| Promise<number> | Promise used to return the number of free bytes obtained.| **Example** @@ -51,10 +54,10 @@ Obtains the number of free bytes of the specified file system in asynchronous mo **Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------- | ---- | ---------------------------- | - | path | string | Yes | File path of the file system.| - | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of free bytes obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of free bytes obtained.| **Example** @@ -78,15 +81,15 @@ Obtains the total number of bytes of the specified file system in asynchronous m **Parameters** - | Name| Type | Mandatory| Description | - | ---- | ------ | ---- | ---------------------------- | - | path | string | Yes | File path of the file system.| +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| **Return value** - | Type | Description | - | --------------------- | ------------ | - | Promise<number> | Promise used to return the total number of bytes obtained.| +| Type | Description | +| --------------------- | ------------ | +| Promise<number> | Promise used to return the total number of bytes obtained.| **Example** @@ -109,10 +112,10 @@ Obtains the total number of bytes of the specified file system in asynchronous m **Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------- | ---- | ---------------------------- | - | path | string | Yes | File path of the file system.| - | callback | AsyncCallback<number> | Yes | Callback invoked to return the total number of bytes obtained. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| path | string | Yes | File path of the file system.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the total number of bytes obtained. | **Example** diff --git a/en/application-dev/reference/errorcodes/errorcode-filemanagement.md b/en/application-dev/reference/errorcodes/errorcode-filemanagement.md index 42192691a4127493dfe94fbef0d67135f870a253..2c352ff97bc21223625ffc048353711b949e040a 100644 --- a/en/application-dev/reference/errorcodes/errorcode-filemanagement.md +++ b/en/application-dev/reference/errorcodes/errorcode-filemanagement.md @@ -1,10 +1,5 @@ # File Management Error Codes -The error codes of the file management subsystem consist of the following: - -- Basic file I/O error codes -- User data management error codes -- User file access error codes -- Spatial statistics error codes +The error codes of the file management subsystem consist of the following:
- Basic file I/O error codes
- User data management error codes
- User file access error codes
- Spatial statistics error codes ## Basic File I/O Error Codes @@ -719,3 +714,41 @@ Fail to notify agent **Solution** Check whether the client is normal. + +## Error Code Adaptation +The APIs provided by the file management subsystem support exception handling. +Sample code for exception handling in a synchronous API: +```js +import fs from '@ohos.file.fs' + +try { + let file = fs.openSync(path, fs.OpenMode.READ_ONLY); +} catch (err) { + console.error("openSync errCode:" + err.code + ", errMessage:" + err.message); +} +``` +Sample code for exception handling in an asynchronous API (promise): +```js +import fs from '@ohos.file.fs' + +try { + let file = await fs.open(path, fs.OpenMode.READ_ONLY); +} catch (err) { + console.error("open promise errCode:" + err.code + ", errMessage:" + err.message); +} +``` + +Sample code for exception handling in an asynchronous API (callback): +```js +import fs from '@ohos.file.fs' + +try { + fs.open(path, fs.OpenMode.READ_ONLY, function(e, file){ // Asynchronous thread (such as the system call) errors are obtained via a callback. + if (e) { + console.error("open in async errCode:" + e.code + ", errMessage:" + e.message); + } + }); +} catch (err) {// Main thread errors (such as invalid parameters) are obtained by try catch. + console.error("open callback errCode:" + err.code + ", errMessage:" + err.message); +} +```