-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileio.js
86 lines (81 loc) · 2.15 KB
/
fileio.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"use strict";
/*
This is a file from Vanilla-Tools (https://github.com/suppenhuhn79/vanilla-tools)
Copyright 2021 Christoph Zager, licensed under the Apache License, Version 2.0
See the full license text at http://www.apache.org/licenses/LICENSE-2.0
*/
const fileIo = {};
fileIo.offerFileToClient = function (filename, data, type = "text/plain")
{
let anchorNode = document.createElement("a");
anchorNode.style.display = "none";
let file = new Blob([data], {"type": type});
anchorNode.href = URL.createObjectURL(file);
anchorNode.download = String(filename).replace(/[^a-z0-9\s\-_.]/ig, "");
document.body.appendChild(anchorNode);
anchorNode.click();
anchorNode.remove();
}
fileIo.requestClientFile = function (clickEvent)
{
return new Promise((resolve, reject) =>
{
let inputNode = document.createElement("input");
inputNode.setAttribute("type", "file");
inputNode.setAttribute("accept", "text/plain");
inputNode.style.display = "none";
inputNode.onchange = (fileEvent) =>
{
let fileReader = new FileReader();
fileReader.onload = (evt) => resolve(evt);
fileReader.readAsText(fileEvent.target.files[0]);
};
document.body.appendChild(inputNode);
inputNode.click();
inputNode.remove();
});
}
fileIo.fetchServerFile = function (url, autoRecognizeDataType = true)
{
return new Promise((resolve, reject) =>
{
let httpRequest = new XMLHttpRequest();
httpRequest.open("GET", url);
httpRequest.onloadend = (httpEvent) =>
{
let result = httpEvent.target.responseText;
if (httpEvent.target.status !== 200)
{
reject(new ReferenceError("Getting \"" + url + "\" returned HTTP status code " + httpEvent.target.status));
}
else
{
if (autoRecognizeDataType)
{
try
{
let fileExt = /\.([^.]+)$/.exec(url.toLowerCase());
if (!!fileExt)
{
switch (fileExt[1])
{
case "json":
result = JSON.parse(result);
break;
case "xml":
result = new DOMParser().parseFromString(result, "text/xml");
break;
}
}
}
catch (ex)
{
reject(new SyntaxError(ex.message));
}
}
}
resolve(result);
}
httpRequest.send();
});
}