1 |
|
2 | 'use strict';
|
3 |
|
4 | const fs = require('fs');
|
5 | const fileSorter = require('./filesorter');
|
6 | const initMetadataService = require('../src/metadata');
|
7 |
|
8 | const Readable = require('stream').Readable;
|
9 |
|
10 |
|
11 | class SVGIconsDirStream extends Readable {
|
12 | constructor(dir, options) {
|
13 | super({ objectMode: true });
|
14 | this.getMetadata = options.metadataProvider || initMetadataService(options);
|
15 | this.gotFilesInfos = false;
|
16 | this.dir = dir;
|
17 |
|
18 | if (dir instanceof Array) {
|
19 | const dirCopy = this.dir;
|
20 |
|
21 | this.dir = '';
|
22 | this._getFilesInfos(dirCopy);
|
23 | }
|
24 | }
|
25 | _getFilesInfos(files) {
|
26 | let filesProcessed = 0;
|
27 |
|
28 | this.fileInfos = [];
|
29 |
|
30 | files = files.slice(0).sort(fileSorter);
|
31 | files.forEach((file) => {
|
32 | this.getMetadata(
|
33 | (this.dir ? this.dir + '/' : '') + file,
|
34 | (err, metadata) => {
|
35 | filesProcessed++;
|
36 | if (err) {
|
37 | this.emit('error', err);
|
38 | } else {
|
39 | if (metadata.renamed) {
|
40 | this.options.log(
|
41 | 'Saved codepoint: ' +
|
42 | 'u' +
|
43 | metadata.unicode[0]
|
44 | .codePointAt(0)
|
45 | .toString(16)
|
46 | .toUpperCase() +
|
47 | ' for the glyph "' +
|
48 | metadata.name +
|
49 | '"'
|
50 | );
|
51 | }
|
52 | this.fileInfos.push(metadata);
|
53 | }
|
54 | if (files.length === filesProcessed) {
|
55 |
|
56 | this.fileInfos.sort((infosA, infosB) =>
|
57 | infosA.unicode[0] > infosB.unicode[0] ? 1 : -1
|
58 | );
|
59 |
|
60 | this.gotFilesInfos = true;
|
61 |
|
62 | this._pushSVGIcons();
|
63 | }
|
64 | }
|
65 | );
|
66 | });
|
67 | }
|
68 |
|
69 | _pushSVGIcons() {
|
70 | let fileInfo;
|
71 | let svgIconStream;
|
72 |
|
73 | while (this.fileInfos.length) {
|
74 | fileInfo = this.fileInfos.shift();
|
75 | svgIconStream = fs.createReadStream(fileInfo.path);
|
76 | svgIconStream.metadata = {
|
77 | name: fileInfo.name,
|
78 | unicode: fileInfo.unicode,
|
79 | };
|
80 | if (!this.push(svgIconStream)) {
|
81 | return;
|
82 | }
|
83 | }
|
84 | this.push(null);
|
85 | }
|
86 | _read() {
|
87 | if (!this.fileInfos) {
|
88 | fs.readdir(this.dir, (err, files) => {
|
89 | if (err) {
|
90 | this.emit('error', err);
|
91 | }
|
92 | this._getFilesInfos(files);
|
93 | });
|
94 | return;
|
95 | }
|
96 | if (this.gotFilesInfos) {
|
97 | this._pushSVGIcons();
|
98 | }
|
99 | }
|
100 | }
|
101 |
|
102 | module.exports = SVGIconsDirStream;
|