• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Lightweight Data Store Development
2
3## When to Use
4
5The lightweight data store is ideal for storing lightweight and frequently used data, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the  **Storage**  APIs.
6
7## Available APIs
8
9The lightweight data store provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value pairs. Keys are of the string type, and values can be of the number, string, or Boolean type.
10
11**Creating a Storage Instance**
12
13Create a  **Storage**  instance for data operations. A  **Storage**  instance is created after data is read from a specified file and loaded to the instance.
14
15**Table  1**  API for creating a  **Storage**  instance
16
17| Package Name      | Method                                      | Description                                                  |
18| ----------------- | ------------------------------------------- | ------------------------------------------------------------ |
19| ohos.data.storage | getStorage(path: string): Promise\<Storage> | Obtains the **Storage** singleton corresponding to a file for data operations. |
20
21**Writing Data**
22
23Call the  **put\(\)**  method to add or modify data in a  **Storage**  instance.
24
25**Table  2**  API for writing data
26
27| Class   | Method                                             | Description                                           |
28| ------- | -------------------------------------------------- | ----------------------------------------------------- |
29| Storage | put(key: string, value: ValueType): Promise\<void> | Writes data of the number, string, and Boolean types. |
30
31**Reading Data**
32
33Call the  **get\(\)**  method to read data from a  **Storage**  instance.
34
35**Table  3**  API for reading data
36
37| Class   | Method                                                     | Description                                          |
38| ------- | ---------------------------------------------------------- | ---------------------------------------------------- |
39| Storage | get(key: string, defValue: ValueType): Promise\<ValueType> | Reads data of the number, string, and Boolean types. |
40
41**Storing Data Persistently**
42
43Call the  **flush\(\)**  method to write the cached data back to its text file for persistent storage.
44
45**Table  4**  API for data persistence
46
47| Class   | Method                  | Description                                                  |
48| ------- | ----------------------- | ------------------------------------------------------------ |
49| Storage | flush(): Promise\<void> | Writes data in the **Storage** instance back to its file through an asynchronous thread. |
50
51**Observing Data Changes**
52
53Specify  **StorageObserver**  as the callback to subscribe to data changes. When the value of the subscribed key is changed and the  **flush\(\)**  method is executed,  **StorageObserver**  will be invoked.
54
55**Table  5**  APIs for subscribing to data changes
56
57| Class   | Method                                                       | Description                     |
58| ------- | ------------------------------------------------------------ | ------------------------------- |
59| Storage | on(type: 'change', callback: Callback\<StorageObserver>): void | Subscribes to data changes.     |
60| Storage | off(type: 'change', callback: Callback\<StorageObserver>): void | Unsubscribes from data changes. |
61
62**Deleting Data**
63
64Use the following APIs to delete a  **Storage**  instance or data file.
65
66**Table  6**  APIs for deleting data
67
68| Package Name      | Method                                               | Description                                                  |
69| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ |
70| ohos.data.storage | deleteStorage(path: string): Promise\<void>          | Deletes a **Storage** instance from the cache and deletes its file from the device. |
71| ohos.data.storage | removeStorageFromCache(path: string): Promise\<void> | Deletes a **Storage** instance from the cache to release memory. |
72
73
74## How to Develop
75
761.  Import  **@ohos.data.storage**  and related modules to the development environment.
77
78    ```js
79    import dataStorage from '@ohos.data.storage';
80    import featureAbility from '@ohos.ability.featureAbility';  // Used to obtain the file storage path.
81    ```
82
832.  Create a  **Storage**  instance.
84
85    Read the specified file and load its data to the  **Storage**  instance for data operations.
86
87   ```js
88   var path;
89   var context = featureAbility.getContext();
90   context.getFilesDir().then((filePath) => {
91       path = filePath;
92       console.info("======================>getFilesDirPromsie====================>");
93
94       let promise = dataStorage.getStorage(path + '/mystore');
95   });
96   ```
97
98
993.  Write data.
100
101    Use the  **put\(\)**  method of the  **Storage**  class to write data to the cached  **Storage**  instance.
102
103    ```js
104    promise.then((storage) => {
105        let getPromise = storage.put('startup', 'auto'); // Save data to the Storage instance.
106        getPromise.then(() => {
107            console.info("Succeeded in putting the value of startup.");
108        }).catch((err) => {
109            console.info("Failed to put the value of startup with err: " + err);
110        })
111    }).catch((err) => {
112        console.info("Failed to get the storage.");
113    })
114    ```
115
116
1174.  Read data.
118
119    Use the  **get\(\)**  method of the  **Storage**  class to read data.
120
121   ```js
122   promise.then((storage) => {
123       let getPromise = storage.get('startup', 'default')
124       getPromise.then((value) => {
125           console.info("The value of startup is " + value);
126       }).catch((err) => {
127           console.info("Failed to get the value of startup with err: " + err);
128       })
129   }).catch((err) => {
130       console.info("Failed to get the storage.")
131
132   })
133   ```
134
135
1365.  Store data persistently.
137
138    Use the  **flush**  or  **flushSync**  method to flush data in the  **Storage**  instance to its file.
139
140    ```js
141    storage.flush();
142    ```
143
1446.  Observe data changes.
145
146    Specify  **StorageObserver**  as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the  **flush\(\)**  method is executed,  **StorageObserver**  will be invoked. Unregister the  **StorageObserver**  when it is no longer required.
147
148   ```js
149   promise.then((storage) => {
150       var observer = function (key) {
151           console.info("The key of " + key + " changed.");
152       }
153       storage.on('change', observer)
154       storage.putSync('startup', 'auto'); // Modify data in the Storage instance.
155       storage.flushSync(); // Trigger the StorageObserver callback.
156
157       storage.off('change', observer); // Unsubscribe from the data changes.
158   }).catch((err) => {
159       console.info("Failed to get the storage.");
160   })
161   ```
162
163
1647.  Delete the specified file.
165
166    Use the  **deleteStorage**  method to delete the  **Storage**  singleton of the specified file from the memory, and delete the specified file, its backup file, and damaged files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored.
167
168   ```js
169   let promise = dataStorage.deleteStorage(path + '/mystore');
170   promise.then(() => {
171       console.info("Succeeded in deleting the storage.");
172   }).catch((err) => {
173       console.info("Failed to delete the storage with err: " + err);
174
175   })
176   ```
177