• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.data.storage (Lightweight Data Storage)
2
3The **DataStorage** module provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type.
4
5
6> **NOTE**
7>
8> -  The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
9>
10> -  The APIs of this module are no longer maintained since API version 9. You are advised to use [@ohos.data.preferences](js-apis-data-preferences.md).
11>
12> -  The APIs of this module can be used only in the FA model.
13
14
15## Modules to Import
16
17```js
18import data_storage from '@ohos.data.storage';
19```
20
21## Constants
22
23**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
24
25| Name            | Type| Readable| Writable| Description                                 |
26| ---------------- | -------- | ---- | ---- | ------------------------------------- |
27| MAX_KEY_LENGTH   | number   | Yes  | No  | Maximum length of a key, which is 80 bytes.    |
28| MAX_VALUE_LENGTH | number   | Yes  | No  | Maximum length of a value, which is 8192 bytes.|
29
30
31## data_storage.getStorageSync
32
33getStorageSync(path: string): Storage
34
35Reads the specified file and loads its data to the **Storage** instance for data operations.
36
37**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
38
39**Parameters**
40
41| Name| Type  | Mandatory| Description                      |
42| ------ | ------ | ---- | -------------------------- |
43| path   | string | Yes  | Path of the target file.|
44
45**Return value**
46
47| Type               | Description                                             |
48| ------------------- | ------------------------------------------------- |
49| [Storage](#storage) | **Storage** instance used for data storage operations.|
50
51**Example**
52
53```js
54import featureAbility from '@ohos.ability.featureAbility';
55
56let path;
57let context = featureAbility.getContext();
58context.getFilesDir().then((filePath) => {
59  path = filePath;
60  console.info("======================>getFilesDirPromise====================>");
61
62  let storage = data_storage.getStorageSync(path + '/mystore');
63  storage.putSync('startup', 'auto');
64  storage.flushSync();
65});
66```
67
68
69## data_storage.getStorage
70
71getStorage(path: string, callback: AsyncCallback<Storage>): void
72
73Reads the specified file and loads its data to the **Storage** instance for data operations. This API uses an asynchronous callback to return the result.
74
75**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
76
77**Parameters**
78
79| Name  | Type                                    | Mandatory| Description                      |
80| -------- | ---------------------------------------- | ---- | -------------------------- |
81| path     | string                                   | Yes  | Path of the target file.|
82| callback | AsyncCallback<[Storage](#storage)> | Yes  | Callback invoked to return the result.                |
83
84**Example**
85
86```js
87import featureAbility from '@ohos.ability.featureAbility';
88
89let path;
90let context = featureAbility.getContext();
91context.getFilesDir().then((filePath) => {
92  path = filePath;
93  console.info("======================>getFilesDirPromise====================>");
94
95  data_storage.getStorage(path + '/mystore', function (err, storage) {
96    if (err) {
97      console.info("Failed to get the storage. path: " + path + '/mystore');
98      return;
99    }
100    storage.putSync('startup', 'auto');
101    storage.flushSync();
102  })
103});
104```
105
106
107## data_storage.getStorage
108
109getStorage(path: string): Promise<Storage>
110
111Reads the specified file and loads its data to the **Storage** instance for data operations. This API uses a promise to return the result.
112
113**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
114
115**Parameters**
116
117| Name| Type  | Mandatory| Description                      |
118| ------ | ------ | ---- | -------------------------- |
119| path   | string | Yes  | Path of the target file.|
120
121**Return value**
122
123| Type                              | Description                           |
124| ---------------------------------- | ------------------------------- |
125| Promise<[Storage](#storage)> | Promise used to return the result.|
126
127**Example**
128
129```js
130import featureAbility from '@ohos.ability.featureAbility';
131
132let path;
133let context = featureAbility.getContext();
134context.getFilesDir().then((filePath) => {
135  path = filePath;
136  console.info("======================>getFilesDirPromise====================>");
137
138  let getPromise = data_storage.getStorage(path + '/mystore');
139  getPromise.then((storage) => {
140    storage.putSync('startup', 'auto');
141    storage.flushSync();
142  }).catch((err) => {
143    console.info("Failed to get the storage. path: " + path + '/mystore');
144  })
145});
146```
147
148
149## data_storage.deleteStorageSync
150
151deleteStorageSync(path: string): void
152
153Deletes the singleton **Storage** instance of a file from the memory, and deletes the specified file, its backup file, and damaged files. After the specified files are deleted, the **Storage** instance cannot be used for data operations. Otherwise, data inconsistency will occur.
154
155**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
156
157**Parameters**
158
159| Name| Type  | Mandatory| Description                      |
160| ------ | ------ | ---- | -------------------------- |
161| path   | string | Yes  | Path of the target file.|
162
163**Example**
164
165```js
166import featureAbility from '@ohos.ability.featureAbility';
167
168let path;
169let context = featureAbility.getContext();
170context.getFilesDir().then((filePath) => {
171    path = filePath;
172    console.info("======================>getFilesDirPromise====================>");
173
174    data_storage.deleteStorageSync(path + '/mystore');
175});
176```
177
178## data_storage.deleteStorage
179
180deleteStorage(path: string, callback: AsyncCallback<void>): void
181
182Deletes the singleton **Storage** instance of a file from the memory, and deletes the specified file, its backup file, and damaged files. After the specified files are deleted, the **Storage** instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses an asynchronous callback to return the result.
183
184**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
185
186**Parameters**
187
188| Name  | Type                     | Mandatory| Description                      |
189| -------- | ------------------------- | ---- | -------------------------- |
190| path     | string                    | Yes  | Path of the target file.|
191| callback | AsyncCallback<void> | Yes       | Callback that returns no value. |
192
193**Example**
194
195```js
196import featureAbility from '@ohos.ability.featureAbility';
197
198let path;
199let context = featureAbility.getContext();
200context.getFilesDir().then((filePath) => {
201  path = filePath;
202  console.info("======================>getFilesDirPromise====================>");
203
204  data_storage.deleteStorage(path + '/mystore', function (err) {
205    if (err) {
206      console.info("Failed to delete the storage with err: " + err);
207      return;
208    }
209    console.info("Succeeded in deleting the storage.");
210  })
211});
212```
213
214
215## data_storage.deleteStorage
216
217deleteStorage(path: string): Promise<void>
218
219Deletes the singleton **Storage** instance of a file from the memory, and deletes the specified file, its backup file, and damaged files. After the specified files are deleted, the **Storage** instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses a promise to return the result.
220
221**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
222
223**Parameters**
224
225| Name| Type  | Mandatory| Description                      |
226| ------ | ------ | ---- | -------------------------- |
227| path   | string | Yes  | Path of the target file.|
228
229**Return value**
230
231| Type               | Description                           |
232| ------------------- | ------------------------------- |
233| Promise<void> | Promise that returns no value. |
234
235**Example**
236
237```js
238import featureAbility from '@ohos.ability.featureAbility';
239
240let path;
241let context = featureAbility.getContext();
242context.getFilesDir().then((filePath) => {
243  path = filePath;
244  console.info("======================>getFilesDirPromise====================>");
245
246  let promisedelSt = data_storage.deleteStorage(path + '/mystore');
247  promisedelSt.then(() => {
248    console.info("Succeeded in deleting the storage.");
249  }).catch((err) => {
250    console.info("Failed to delete the storage with err: " + err);
251  })
252});
253```
254
255
256## data_storage.removeStorageFromCacheSync
257
258removeStorageFromCacheSync(path: string): void
259
260Removes the singleton **Storage** instance of a file from the cache. The removed instance cannot be used for data operations. Otherwise, data inconsistency will occur.
261
262**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
263
264**Parameters**
265| Name| Type  | Mandatory| Description                      |
266| ------ | ------ | ---- | -------------------------- |
267| path   | string | Yes  | Path of the target file.|
268
269**Example**
270
271```js
272import featureAbility from '@ohos.ability.featureAbility';
273
274let path;
275let context = featureAbility.getContext();
276context.getFilesDir().then((filePath) => {
277    path = filePath;
278    console.info("======================>getFilesDirPromise====================>");
279
280    data_storage.removeStorageFromCacheSync(path + '/mystore');
281});
282```
283
284
285## data_storage.removeStorageFromCache
286
287removeStorageFromCache(path: string, callback: AsyncCallback<void>): void
288
289Removes the singleton **Storage** instance of a file from the cache. The removed instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses an asynchronous callback to return the result.
290
291**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
292
293**Parameters**
294
295| Name  | Type                     | Mandatory| Description                      |
296| -------- | ------------------------- | ---- | -------------------------- |
297| path     | string                    | Yes  | Path of the target file.|
298| callback | AsyncCallback<void> | Yes       | Callback that returns no value. |
299
300**Example**
301
302```js
303import featureAbility from '@ohos.ability.featureAbility';
304
305let path;
306let context = featureAbility.getContext();
307context.getFilesDir().then((filePath) => {
308  path = filePath;
309  console.info("======================>getFilesDirPromise====================>");
310
311  data_storage.removeStorageFromCache(path + '/mystore', function (err) {
312    if (err) {
313      console.info("Failed to remove storage from cache with err: " + err);
314      return;
315    }
316    console.info("Succeeded in removing storage from cache.");
317  })
318});
319```
320
321
322## data_storage.removeStorageFromCache
323
324removeStorageFromCache(path: string): Promise<void>
325
326Removes the singleton **Storage** instance of a file from the cache. The removed instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses a promise to return the result.
327
328**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
329
330**Parameters**
331
332| Name| Type  | Mandatory| Description                      |
333| ------ | ------ | ---- | -------------------------- |
334| path   | string | Yes  | Path of the target file.|
335
336**Return value**
337
338| Type               | Description                           |
339| ------------------- | ------------------------------- |
340| Promise<void> | Promise that returns no value. |
341
342**Example**
343
344```js
345import featureAbility from '@ohos.ability.featureAbility';
346
347let path;
348let context = featureAbility.getContext();
349context.getFilesDir().then((filePath) => {
350  path = filePath;
351  console.info("======================>getFilesDirPromise====================>");
352
353  let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore')
354  promiserevSt.then(() => {
355    console.info("Succeeded in removing storage from cache.");
356  }).catch((err) => {
357    console.info("Failed to remove storage from cache with err: " + err);
358  })
359});
360```
361
362## Storage
363
364Provides APIs for obtaining and modifying storage data.
365
366### getSync
367
368getSync(key: string, defValue: ValueType): ValueType
369
370Obtains the value corresponding to a key. If the value is null or not of the default value type, **defValue** is returned.
371
372**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
373
374**Parameters**
375
376| Name  | Type                   | Mandatory| Description                                                        |
377| -------- | ----------------------- | ---- | ------------------------------------------------------------ |
378| key      | string                  | Yes  | Key of the data. It cannot be empty.                             |
379| defValue | [ValueType](#valuetype) | Yes  | Default value to be returned if the value of the specified key does not exist. It can be a number, string, or Boolean value.|
380
381**Return value**
382
383| Type     | Description                                                    |
384| --------- | -------------------------------------------------------- |
385| ValueType | Value corresponding to the specified key. If the value is null or not in the default value format, the default value is returned.|
386
387**Example**
388
389```js
390let value = storage.getSync('startup', 'default');
391console.info("The value of startup is " + value);
392```
393
394
395### get
396
397get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void
398
399Obtains the value corresponding to a key. If the value is null or not of the default value type, **defValue** is returned. This API uses an asynchronous callback to return the result.
400
401**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
402
403**Parameters**
404
405| Name  | Type                          | Mandatory| Description                                     |
406| -------- | ------------------------------ | ---- | ----------------------------------------- |
407| key      | string                         | Yes  | Key of the data. It cannot be empty.          |
408| defValue | [ValueType](#valuetype)        | Yes  | Default value to be returned. It can be a number, string, or Boolean value.|
409| callback | AsyncCallback<ValueType> | Yes  | Callback invoked to return the result.                               |
410
411**Example**
412
413```js
414storage.get('startup', 'default', function(err, value) {
415    if (err) {
416        console.info("Failed to get the value of startup with err: " + err);
417        return;
418      }
419    console.info("The value of startup is " + value);
420})
421```
422
423
424### get
425
426get(key: string, defValue: ValueType): Promise<ValueType>
427
428Obtains the value corresponding to a key. If the value is null or not of the default value type, **defValue** is returned. This API uses a promise to return the result.
429
430**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
431
432**Parameters**
433
434| Name  | Type                   | Mandatory| Description                                     |
435| -------- | ----------------------- | ---- | ----------------------------------------- |
436| key      | string                  | Yes  | Key of the data. It cannot be empty.          |
437| defValue | [ValueType](#valuetype) | Yes  | Default value to be returned. It can be a number, string, or Boolean value.|
438
439**Return value**
440
441| Type                    | Description                           |
442| ------------------------ | ------------------------------- |
443| Promise<ValueType> | Promise used to return the result.|
444
445**Example**
446
447```js
448let promiseget = storage.get('startup', 'default');
449promiseget.then((value) => {
450    console.info("The value of startup is " + value)
451}).catch((err) => {
452    console.info("Failed to get the value of startup with err: " + err);
453})
454```
455
456
457### putSync
458
459putSync(key: string, value: ValueType): void
460
461Obtains the **Storage** instance corresponding to the specified file, writes data to the **Storage** instance using a **Storage** API, and saves the modification using **flush()** or **flushSync()**.
462
463**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
464
465**Parameters**
466
467| Name| Type                   | Mandatory| Description                                     |
468| ------ | ----------------------- | ---- | ----------------------------------------- |
469| key    | string                  | Yes  | Key of the data. It cannot be empty.            |
470| value  | [ValueType](#valuetype) | Yes  | New value to store. It can be a number, string, or Boolean value.|
471
472**Example**
473
474```js
475storage.putSync('startup', 'auto');
476```
477
478
479### put
480
481put(key: string, value: ValueType, callback: AsyncCallback<void>): void
482
483Obtains the **Storage** instance corresponding to the specified file, writes data to the **Storage** instance using a **Storage** API, and saves the modification using **flush()** or **flushSync()**. This API uses an asynchronous callback to return the result.
484
485**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
486
487**Parameters**
488
489| Name  | Type                     | Mandatory| Description                                     |
490| -------- | ------------------------- | ---- | ----------------------------------------- |
491| key      | string                    | Yes  | Key of the data. It cannot be empty.            |
492| value    | [ValueType](#valuetype)   | Yes  | New value to store. It can be a number, string, or Boolean value.|
493| callback | AsyncCallback<void> | Yes       | Callback that returns no value.                              |
494
495**Example**
496
497```js
498storage.put('startup', 'auto', function (err) {
499    if (err) {
500        console.info("Failed to put the value of startup with err: " + err);
501        return;
502    }
503    console.info("Succeeded in putting the value of startup.");
504})
505```
506
507
508### put
509
510put(key: string, value: ValueType): Promise<void>
511
512Obtains the **Storage** instance corresponding to the specified file, writes data to the **Storage** instance using a **Storage** API, and saves the modification using **flush()** or **flushSync()**. This API uses a promise to return the result.
513
514**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
515
516**Parameters**
517
518| Name| Type                   | Mandatory| Description                                     |
519| ------ | ----------------------- | ---- | ----------------------------------------- |
520| key    | string                  | Yes  | Key of the data. It cannot be empty.            |
521| value  | [ValueType](#valuetype) | Yes  | New value to store. It can be a number, string, or Boolean value.|
522
523**Return value**
524
525| Type               | Description                       |
526| ------------------- | --------------------------- |
527| Promise<void> | Promise that returns no value. |
528
529**Example**
530
531```js
532let promiseput = storage.put('startup', 'auto');
533promiseput.then(() => {
534    console.info("Succeeded in putting the value of startup.");
535}).catch((err) => {
536    console.info("Failed to put the value of startup with err: " + err);
537})
538```
539
540
541### hasSync
542
543hasSync(key: string): boolean
544
545Checks whether the storage object contains data with a given key.
546
547**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
548
549**Parameters**
550
551| Name| Type  | Mandatory| Description                           |
552| ------ | ------ | ---- | ------------------------------- |
553| key    | string | Yes  | Key of the data. It cannot be empty.|
554
555**Return value**
556
557| Type   | Description                                 |
558| ------- | ------------------------------------- |
559| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise.|
560
561**Example**
562
563```js
564let isExist = storage.hasSync('startup');
565if (isExist) {
566    console.info("The key of startup is contained.");
567}
568```
569
570
571### has
572
573has(key: string, callback: AsyncCallback<boolean>): boolean
574
575Checks whether the storage object contains data with a given key. This API uses an asynchronous callback to return the result.
576
577**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
578
579**Parameters**
580
581| Name  | Type                        | Mandatory| Description                           |
582| -------- | ---------------------------- | ---- | ------------------------------- |
583| key      | string                       | Yes  | Key of the data. It cannot be empty.|
584| callback | AsyncCallback<boolean> | Yes  | Callback invoked to return the result.                     |
585
586**Return value**
587
588| Type   | Description                           |
589| ------- | ------------------------------- |
590| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise.|
591
592**Example**
593
594```js
595storage.has('startup', function (err, isExist) {
596    if (err) {
597        console.info("Failed to check the key of startup with err: " + err);
598        return;
599    }
600    if (isExist) {
601        console.info("The key of startup is contained.");
602    }
603})
604```
605
606
607### has
608
609has(key: string): Promise<boolean>
610
611Checks whether the storage object contains data with a given key. This API uses a promise to return the result.
612
613**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
614
615**Parameters**
616
617| Name| Type  | Mandatory| Description                           |
618| ------ | ------ | ---- | ------------------------------- |
619| key    | string | Yes  | Key of the data. It cannot be empty.|
620
621**Return value**
622
623| Type                  | Description                       |
624| ---------------------- | --------------------------- |
625| Promise<boolean> | Promise used to return the result.|
626
627**Example**
628
629```js
630let promisehas = storage.has('startup')
631promisehas.then((isExist) => {
632    if (isExist) {
633        console.info("The key of startup is contained.");
634    }
635}).catch((err) => {
636    console.info("Failed to check the key of startup with err: " + err);
637})
638```
639
640
641### deleteSync
642
643deleteSync(key: string): void
644
645Deletes data with the specified key from this storage object.
646
647**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
648
649**Parameters**
650
651| Name| Type  | Mandatory| Description                             |
652| ------ | ------ | ---- | --------------------------------- |
653| key    | string | Yes  | Key of the data. It cannot be empty.|
654
655**Example**
656
657```js
658 storage.deleteSync('startup');
659```
660
661
662### delete
663
664delete(key: string, callback: AsyncCallback<void>): void
665
666Deletes data with the specified key from this storage object. This API uses an asynchronous callback to return the result.
667
668**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
669
670**Parameters**
671
672| Name  | Type                     | Mandatory| Description                           |
673| -------- | ------------------------- | ---- | ------------------------------- |
674| key      | string                    | Yes  | Key of the data. It cannot be empty.|
675| callback | AsyncCallback<void> | Yes       | Callback that returns no value.      |
676
677**Example**
678
679```js
680storage.delete('startup', function (err) {
681    if (err) {
682        console.info("Failed to delete startup key failed err: " + err);
683        return;
684    }
685    console.info("Succeeded in deleting startup key.");
686})
687```
688
689
690### delete
691
692delete(key: string): Promise<void>
693
694Deletes data with the specified key from this storage object. This API uses a promise to return the result.
695
696**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
697
698**Parameters**
699
700| Name| Type  | Mandatory| Description                 |
701| ------ | ------ | ---- | --------------------- |
702| key    | string | Yes  | Key of the data.|
703
704**Return value**
705
706| Type               | Description                       |
707| ------------------- | --------------------------- |
708| Promise<void> | Promise that returns no value. |
709
710**Example**
711
712```js
713let promisedel = storage.delete('startup')
714promisedel.then(() => {
715    console.info("Succeeded in deleting startup key.");
716}).catch((err) => {
717    console.info("Failed to delete startup key failed err: " + err);
718})
719```
720
721
722### flushSync
723
724flushSync(): void
725
726Saves the modification of this object to the **Storage** instance and synchronizes the modification to the file.
727
728**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
729
730**Example**
731
732```js
733storage.flushSync();
734```
735
736
737### flush
738
739flush(callback: AsyncCallback<void>): void
740
741Saves the modification of this object to the **Storage** instance and synchronizes the modification to the file. This API uses an asynchronous callback to return the result.
742
743**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
744
745**Parameters**
746
747| Name  | Type                     | Mandatory| Description      |
748| -------- | ------------------------- | ---- | ---------- |
749| callback | AsyncCallback<void> | Yes       | Callback that returns no value. |
750
751**Example**
752
753```js
754storage.flush(function (err) {
755    if (err) {
756        console.info("Failed to flush to file with err: " + err);
757        return;
758    }
759    console.info("Succeeded in flushing to file.");
760})
761```
762
763
764### flush
765
766flush(): Promise<void>
767
768Saves the modification of this object to the **Storage** instance and synchronizes the modification to the file. This API uses a promise to return the result.
769
770**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
771
772**Return value**
773
774| Type               | Description                       |
775| ------------------- | --------------------------- |
776| Promise<void> | Promise that returns no value. |
777
778**Example**
779
780```js
781let promiseflush = storage.flush();
782promiseflush.then(() => {
783    console.info("Succeeded in flushing to file.");
784}).catch((err) => {
785    console.info("Failed to flush to file with err: " + err);
786})
787```
788
789
790### clearSync
791
792clearSync(): void
793
794Clears this **Storage** object.
795
796**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
797
798**Example**
799
800```js
801storage.clearSync();
802```
803
804
805### clear
806
807clear(callback: AsyncCallback<void>): void
808
809Clears this **Storage** object. This API uses an asynchronous callback to return the result.
810
811**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
812
813**Parameters**
814
815| Name  | Type                     | Mandatory| Description      |
816| -------- | ------------------------- | ---- | ---------- |
817| callback | AsyncCallback<void> | Yes       | Callback that returns no value. |
818
819**Example**
820
821```js
822storage.clear(function (err) {
823    if (err) {
824        console.info("Failed to clear the storage with err: " + err);
825        return;
826    }
827    console.info("Succeeded in clearing the storage.");
828})
829```
830
831
832### clear
833
834clear(): Promise<void>
835
836Clears this **Storage** object. This API uses a promise to return the result.
837
838**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
839
840**Return value**
841| Type               | Description                       |
842| ------------------- | --------------------------- |
843| Promise<void> | Promise that returns no value. |
844
845**Example**
846
847```js
848let promiseclear = storage.clear();
849promiseclear.then(() => {
850    console.info("Succeeded in clearing the storage.");
851}).catch((err) => {
852    console.info("Failed to clear the storage with err: " + err);
853})
854```
855
856
857### on('change')
858
859on(type: 'change', callback: Callback<StorageObserver>): void
860
861Subscribes to data changes. The **StorageObserver** needs to be implemented. When the value of the key subscribed to is changed, a callback will be invoked after **flush()** or **flushSync()** is executed.
862
863**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
864
865**Parameters**
866
867| Name  | Type                                               |  Mandatory| Description                                    |
868| -------- | --------------------------------------------------- | ------ |---------------------------------------- |
869| type     | string                                              |Yes| Event type. The value **change** indicates data change events.|
870| callback | Callback<[StorageObserver](#storageobserver)> | Yes|Callback invoked to return the data change.                          |
871
872**Example**
873
874```js
875let observer = function (key) {
876    console.info("The key of " + key + " changed.");
877}
878storage.on('change', observer);
879storage.putSync('startup', 'auto');
880storage.flushSync();  // observer will be called.
881```
882
883
884### off('change')
885
886off(type: 'change', callback: Callback<StorageObserver>): void
887
888Unsubscribes from data changes.
889
890**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
891
892**Parameters**
893
894| Name  | Type                                               | Mandatory|  Description                                |
895| -------- | --------------------------------------------------- | ------ |---------------------------------------- |
896| type     | string                                              |Yes| Event type. The value **change** indicates data change events.|
897| callback | Callback<[StorageObserver](#storageobserver)> | Yes|Callback for the data change.                |
898
899**Example**
900
901```js
902let observer = function (key) {
903    console.info("The key of " + key + " changed.");
904}
905storage.off('change', observer);
906```
907
908
909## StorageObserver
910
911**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
912
913| Name| Type| Mandatory| Description            |
914| ---- | -------- | ---- | ---------------- |
915| key  | string   | No  | Data changed.|
916
917## ValueType
918
919Enumerates the value types.
920
921**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
922
923| Type   | Description                |
924| ------- | -------------------- |
925| number  | The value is a number.  |
926| string  | The value is a string.  |
927| boolean | The value is of Boolean type.|
928