UNPKG

1.35 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5const fs_1 = require("fs");
6const mimer_1 = __importDefault(require("mimer"));
7const uriTemplate_1 = require("./template/uriTemplate");
8const { readFile } = fs_1.promises;
9class DataURIParser {
10 async encode(fileName, handler) {
11 try {
12 const buffer = await readFile(fileName);
13 this.format(fileName, buffer);
14 handler && handler(undefined, this.content, this);
15 return this.content;
16 }
17 catch (err) {
18 if (handler) {
19 handler(err);
20 return;
21 }
22 throw err;
23 }
24 }
25 format(fileName, fileContent) {
26 const fileBuffer = fileContent instanceof Buffer ? fileContent : Buffer.from(fileContent);
27 this.buffer = fileBuffer;
28 this.base64 = fileBuffer.toString('base64');
29 this.createMetadata(fileName);
30 return this;
31 }
32 createMetadata(fileName) {
33 const { base64, mimetype = mimer_1.default(fileName) } = this;
34 this.fileName = fileName;
35 this.mimetype = mimetype;
36 this.content = uriTemplate_1.uriParser({ base64, mimetype });
37 return this;
38 }
39}
40module.exports = DataURIParser;