UNPKG

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