UNPKG

2.15 kBJavaScriptView Raw
1/**
2 * @author: Akshay
3 * @date: 12/13/2015
4 * @github: https://github.com/akshayKrSingh
5 * @npm: https://npmjs.com/~akshaysingh
6 */
7var Writable = require('stream').Writable;
8var EpubHelpers = require('../epub/helpers');
9var utils = require('util');
10var path = require('path');
11var stripTags = require('striptags');
12var js2xml = require('js2xmlparser');
13var fs = require('fs-extra');
14var pretty = require('pretty-data').pd;
15
16function Editor(options) {
17 if (!(this instanceof Editor)) {
18 return new Editor(options);
19 }
20
21 this.options = options || {};
22 this._$$count = 0;
23 this._$$Spines = {total: 0, '_struct': {spine: []}};
24 this.opf = {
25 root: '',
26 path: ''
27 };
28
29 Writable.call(this, options);
30}
31
32utils.inherits(Editor, Writable);
33
34var proto = Editor.prototype;
35
36proto._write = function(chunk, enc, next) {
37 var data = JSON.parse(chunk.toString()), epub = EpubHelpers(), self = this;
38
39 if (data.spineLength) {self._$$Spines.total = data.spineLength;}
40
41 if (data.type === 'EPUB#spine') {
42 self._$$Spines._struct.spine.push({
43 '@': {
44 id: data.idref,
45 href: data.href
46 },
47 "#": stripTags(data.file)
48 });
49 //console.log(stripTags(data.file));
50 }
51
52 if (self._$$count === self._$$Spines.total - 1) {
53 fs.outputFile(path.resolve(data.base, 'META-INF/search.xml'),
54 pretty.xml(js2xml('search', self._$$Spines._struct)),
55 function(err) {
56 if (err) {
57 return self._destroy(err);
58 }
59 });
60
61 self._autoDrain();
62 } else if (data.type === 'EPUB#spine') {
63 self._$$count++;
64 }
65
66 next();
67};
68
69/**
70 * @name: _autoDrain()
71 * @description:
72 * Removes Reader properties used during stream _read & _write process.
73 * _autoDrain() is called automatically at the end of Writable Stream.
74 */
75proto._autoDrain = function() {
76 var self = this;
77 self._$$Spines = {total: 0, '_struct': {spine: []}};
78 self._$$count = 0;
79};
80
81proto._destroy = function(err) {
82 // Allows to destruct the stream, nothing will be emitted after this point. No Warnings or Errors
83 this.writeable = false;
84 this._$$destroyed = true;
85 this.emit('close', err);
86};
87
88module.exports = Editor;