cray
Version:
Epub parser
89 lines (74 loc) • 2.24 kB
JavaScript
/**
* @author: Akshay
* @date: 12/13/2015
* @github: https://github.com/akshayKrSingh
* @npm: https://npmjs.com/~akshaysingh
*/
var Writable = require('stream').Writable;
var EpubHelpers = require('../epub/helpers');
var utils = require('util');
var path = require('path');
var stripTags = require('striptags');
var js2xml = require('js2xmlparser');
var fs = require('fs-extra');
var pretty = require('pretty-data').pd;
function Editor(options) {
if (!(this instanceof Editor)) {
return new Editor(options);
}
this.options = options || {};
this._$$count = 0;
this._$$Spines = {total: 0, '_struct': {spine: []}};
this.opf = {
root: '',
path: ''
};
Writable.call(this, options);
}
utils.inherits(Editor, Writable);
var proto = Editor.prototype;
proto._write = function(chunk, enc, next) {
var data = JSON.parse(chunk.toString()), epub = EpubHelpers(), self = this;
if (data.spineLength) {self._$$Spines.total = data.spineLength;}
if (data.type === 'EPUB#spine') {
self._$$Spines._struct.spine.push({
'@': {
id: data.idref,
href: data.href
},
"#": stripTags(data.file)
});
//console.log(stripTags(data.file));
}
if (self._$$count === self._$$Spines.total - 1) {
fs.outputFile(path.resolve(data.base, 'META-INF/search.xml'),
pretty.xml(js2xml('search', self._$$Spines._struct)),
function(err) {
if (err) {
return self._destroy(err);
}
});
self._autoDrain();
} else if (data.type === 'EPUB#spine') {
self._$$count++;
}
next();
};
/**
* @name: _autoDrain()
* @description:
* Removes Reader properties used during stream _read & _write process.
* _autoDrain() is called automatically at the end of Writable Stream.
*/
proto._autoDrain = function() {
var self = this;
self._$$Spines = {total: 0, '_struct': {spine: []}};
self._$$count = 0;
};
proto._destroy = function(err) {
// Allows to destruct the stream, nothing will be emitted after this point. No Warnings or Errors
this.writeable = false;
this._$$destroyed = true;
this.emit('close', err);
};
module.exports = Editor;