1 | 'use strict';
|
2 | const path = require('path');
|
3 | const fs = require('fs');
|
4 | const mimer = require('mimer');
|
5 | const getDimensions = require('image-size');
|
6 | const uri = require('./template/uri');
|
7 | const css = require('./template/css');
|
8 | const Stream = require('stream');
|
9 |
|
10 | class Api extends Stream {
|
11 | constructor() {
|
12 | super();
|
13 |
|
14 | this.readable = true;
|
15 | }
|
16 |
|
17 | format(fileName, fileContent) {
|
18 | const fileBuffer = (fileContent instanceof Buffer) ? fileContent : new Buffer(fileContent);
|
19 |
|
20 | this.base64 = fileBuffer.toString('base64');
|
21 | this.createMetadata(fileName);
|
22 |
|
23 | return this;
|
24 | }
|
25 |
|
26 | createMetadata(fileName) {
|
27 | this.fileName = fileName;
|
28 | this.mimetype = mimer(fileName);
|
29 | this.content = uri(this);
|
30 |
|
31 | return this;
|
32 | }
|
33 |
|
34 | runCallback(handler, err) {
|
35 | if (err) {
|
36 | return handler(err);
|
37 | }
|
38 |
|
39 | return handler.call(this, null, this.content, this);
|
40 | }
|
41 |
|
42 | encode(fileName, handler) {
|
43 | return this.async(fileName, err => handler && this.runCallback(handler, err));
|
44 | }
|
45 |
|
46 | async(fileName, handler) {
|
47 | const base64Chunks = [];
|
48 | const propagateStream = chunk => this.emit('data', chunk);
|
49 |
|
50 | propagateStream(this.createMetadata(fileName).content);
|
51 | fs.createReadStream(fileName, { 'encoding': 'base64' })
|
52 | .on('data', propagateStream)
|
53 | .on('data', chunk => base64Chunks.push(chunk))
|
54 | .on('error', err => {
|
55 | handler(err);
|
56 | this.emit('error', err);
|
57 | })
|
58 | .on('end', () => {
|
59 | this.base64 = base64Chunks.join('');
|
60 | this.emit('end');
|
61 | handler.call(this.createMetadata(fileName));
|
62 | this.emit('encoded', this.content, this);
|
63 | });
|
64 | }
|
65 |
|
66 | encodeSync(fileName) {
|
67 | if (!fileName || !fileName.trim || fileName.trim() === '') {
|
68 | throw new Error('Insert a File path as string argument');
|
69 | }
|
70 |
|
71 | if (fs.existsSync(fileName)) {
|
72 | const fileContent = fs.readFileSync(fileName);
|
73 |
|
74 | return this.format(fileName, fileContent).content;
|
75 | }
|
76 |
|
77 | throw new Error(`The file ${fileName} was not found!`);
|
78 | }
|
79 |
|
80 | getCSS(config) {
|
81 | config = config || {};
|
82 | if (!this.content) {
|
83 | throw new Error('Create a data-uri config using the method encodeSync');
|
84 | }
|
85 |
|
86 | config.class = config.class || path.basename(this.fileName, path.extname(this.fileName));
|
87 | config.background = this.content;
|
88 |
|
89 | if (config.width || config.height || config['background-size']) {
|
90 | config.dimensions = getDimensions(this.fileName);
|
91 | }
|
92 |
|
93 | return css(config);
|
94 | }
|
95 | }
|
96 |
|
97 | module.exports = Api;
|