-
Notifications
You must be signed in to change notification settings - Fork 0
/
cordovaFile.js
67 lines (59 loc) · 1.68 KB
/
cordovaFile.js
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
const sanitize = require("sanitize-filename")
const readAsText = require("./readAsText")
const getFs = (exports.getFs = fsType =>
new Promise((resolve, reject) =>
window.resolveLocalFileSystemURL(fsType, resolve, reject)
))
exports.getFile = args => {
const { dir, name } = args
return new Promise((resolve, reject) => {
dir.getFile(
sanitize(name),
{ create: true, exclusive: false },
resolve,
reject
)
})
}
function createDir(rootDirEntry, folders) {
return new Promise((resolve, reject) => {
rootDirEntry.getDirectory(
folders[0],
{ create: true, exclusive: false },
function(dirEntry) {
// Recursively add the new subfolder (if we still have another to create).
const foldersRest = folders.slice(1)
if (foldersRest.length) {
createDir(dirEntry, foldersRest)
.then(resolve)
.catch(reject)
} else {
resolve(dirEntry)
}
},
reject
)
})
}
exports.getDir = absolutePath => {
const splitPath = absolutePath.split(":/")
const root = splitPath[0] + ":/"
const dirs = splitPath[1].split("/")
return getFs(root).then(root => {
return createDir(root, dirs)
})
}
exports.writeFile = args => {
const { fileEntry, content, type } = args
const blobContent = new Blob([content], { type })
return new Promise(function(resolve, reject) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = resolve
fileWriter.onerror = reject
fileWriter.write(blobContent)
})
}).then(() => fileEntry)
}
exports.readFile = fileEntry => {
return new Promise(fileEntry.file.bind(fileEntry)).then(readAsText)
}