-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathfile.ts
More file actions
61 lines (55 loc) · 1.43 KB
/
file.ts
File metadata and controls
61 lines (55 loc) · 1.43 KB
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
/**
* Copyright (c) 2021 Hengyang Zhang
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
/**
* Export csv file
*
* @param titleAndData all rows
* @param fileName file name
* @since 0.0.7
*/
export function exportCsv(titleAndData: any[][], fileName: string) {
const csv = titleAndData.map(row => row.reduce((a, b) => `${a},${b}`)).reduce((a, b) => `${a}\r\n${b}`)
const blob = new Blob(['\ufeff' + csv], { type: "text/csv" })
exportBlob(blob, fileName + '.csv')
}
/**
* Export json file
* @param data data
* @param fileName the name of file
* @since 0.0.7
*/
export function exportJson(data: any, fileName: string) {
const jsonStr = JSON.stringify(data)
var blob = new Blob([jsonStr], { type: 'text/json' })
exportBlob(blob, fileName + '.json')
}
/**
* @param fileName The name of file with suffix
*/
function exportBlob(blob: Blob, fileName: string) {
const ele: HTMLElement = document.createElement("a")
const link = ele as HTMLAreaElement
link.href = URL.createObjectURL(blob)
link.hidden = true
link.download = fileName
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
/**
* Check json string and
*
* @param jsonStr json
* @since 0.0.5
*/
export function deserialize(jsonStr: string): any | undefined {
try {
return JSON.parse(jsonStr)
} catch {
return undefined
}
}