【cordova-plugin-file】内部ストレージを使ってみた【Vue】

はじめに

これまではデフォルトの vuex を利用してて、結果的に local storage に保存してましたがされますが、以下の記事によるとセキュリティリスクが高いらしいので自分のアプリからしか利用できない内部ストレージを利用する方法を調べてみたので使い方をメモしておきます。

HTML5 の Local Storage を使ってはいけない(翻訳)

環境

  • cordova-plugin-file: 6.0.2

ライブラリインストール

1
cordova plugin add cordova-plugin-file

データを保存・取得する

操作はデフォルトで非同期なので Promise などを活用して同期処理に修正してます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
export default {
methods: {
async init() {
// データ保存
await this.set_data_to_internal_storage('file_name.txt', 'test data')
// データ取得
const data = await this.get_data_from_internal_storage('file_name.txt')
console.log('data: ' + data)
},
async set_data_to_internal_storage(file_name, data) {
console.log('start set_data_to_internal_storage')
const fileSystem = await new Promise(function(resolve, reject) {
window.resolveLocalFileSystemURL(
// eslint-disable-next-line
cordova.file.dataDirectory,
resolve,
reject
)
})
const fileEntry = await new Promise(function(resolve, reject) {
fileSystem.getFile(
file_name,
{ exclusive: false, create: true },
resolve,
reject
)
})
return new Promise((resolve, reject) => {
fileEntry.createWriter(function(writer) {
console.log('書き込み開始')
// 書き込み終了時の処理を定義する
writer.onwriteend = function(event) {
if (this.error) {
console.log(
'ファイル追記 追記処理中にエラー発生',
this.error,
event
)
// Promiseの結果を返す
reject('reject!!')
} else {
console.log('ファイル追記 成功', event)
// Promiseの結果を返す
resolve('resolve!!')
}
}
// 書き込み
writer.write(data)
})
})
},
async get_data_from_internal_storage(file_name) {
console.log('start get_data_from_internal_storage')
var options = {
exclusive: false,
create: false
}
const fileSystem = await new Promise(function(resolve, reject) {
window.resolveLocalFileSystemURL(
// eslint-disable-next-line
cordova.file.dataDirectory,
resolve,
reject
)
})
const fileEntry = await new Promise(function(resolve, reject) {
fileSystem.getFile(file_name, options, resolve, reject)
})
return new Promise(resolve => {
fileEntry.file(
function(file) {
var reader = new FileReader()

reader.onloadend = function() {
console.log('Successful file read: ' + this.result)
console.log(fileEntry.fullPath + ': ' + this.result)
resolve(this.result)
}

reader.readAsText(file)
},
function(error) {
console.log('readFile エラーが発生', error.code)
}
)
})
}
}
}

参考

Cordova アプリ内でファイル操作を行える「cordova-plugin-file」

以上です。

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×