summaryrefslogtreecommitdiff
path: root/src/lib/ContentMetaData.js
blob: da335ad6e5393679ceb45e6e94861ee3edfaf8c8 (plain)
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
class ContentMetaData {
  constructor(request, defaultCharset = "utf-8") {
    this.defaultCharset = defaultCharset;
    let {responseHeaders} = request;
    for (let h of responseHeaders) {
      if (/^\s*Content-(Type|Disposition)\s*$/i.test(h.name)) {
        this[h.name.split("-")[1].trim().toLowerCase()] = h.value;
      }
    }
  }

  get charset() {
    let charset = this.defaultCharset;
    if (this.type) {
      let m = this.type.match(/;\s*charset\s*=\s*(\S+)/);
      if (m) {
        charset = m[1];
      }
    }
    Object.defineProperty(this, "charset", { value: charset, writable: false, configurable: true });
    return charset;
  }

  createDecoder() {
    try {
      return new TextDecoder(this.charset);
    } catch (e) {
      return new TextDecoder(this.defaultCharset);
    }
  }
};