index.js 1.9 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
var fs = require('fs')
var ejs = require('ejs')
var moment = require('moment')
var uuidGenerator = require('./uuid.js')
var jszip = require('jszip')
var path = require('path')

function d(fname) {
    
    return path.join(__dirname, fname)
}

function fnameEscape(name){
    
    return name.replace(/\\|\/|:|\*|\?|"|<|>|\|/g, '-')
}

W
wizardforcel 已提交
18
function writeEpub(articles, imgs, name, path) {
W
init  
wizardforcel 已提交
19
    
W
wizardforcel 已提交
20 21 22
    name = name || articles[0].title
    path = path || fnameEscape(name) + '.epub'
    if(!path.endsWith('.epub')) path += '.epub'
W
init  
wizardforcel 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
    
    var zip = new jszip();
    zip.file('mimetype', fs.readFileSync(d('./assets/mimetype')));
    zip.file('META-INF/container.xml', fs.readFileSync(d('./assets/container.xml')));
    zip.file('OEBPS/Styles/Style.css', fs.readFileSync(d('./assets/Style.css')));
    
    var articleTemp = ejs.compile(fs.readFileSync(d('assets/article.ejs'), 'utf-8'))
    
    var htmlToc = []
    var imgToc = []
    
    for(var [i, art] of Object.entries(articles)) {
        zip.file(`OEBPS/Text/${+i+1}.html`, articleTemp(art));
        
        htmlToc.push({
            title: art.title,
            file: `${+i+1}.html`,
        })
    }
    
飞龙 已提交
43 44
    for(var [fname, data] of imgs.entries()) {
        zip.file(`OEBPS/Images/${fname}`, data);
W
init  
wizardforcel 已提交
45 46
        
        imgToc.push({
飞龙 已提交
47
            file: fname,
W
init  
wizardforcel 已提交
48 49 50 51 52 53 54 55 56 57
        })
    }
    
    var uuid = uuidGenerator.uuid();
    
    var opf = ejs.render(fs.readFileSync(d('assets/content.ejs'), 'utf-8'), {
        date: moment().format('YYYY-MM-DD'),
        imgToc: imgToc,
        htmlToc: htmlToc,
        uuid: uuid,
W
wizardforcel 已提交
58
        name: name,
W
init  
wizardforcel 已提交
59 60 61 62 63 64 65 66 67
    });
    zip.file('OEBPS/content.opf', opf);

    var ncx = ejs.render(fs.readFileSync(d('assets/toc.ejs'), 'utf-8'), {
        toc: htmlToc,
        uuid: uuid,
    });
    zip.file('OEBPS/toc.ncx', ncx);
    
W
wizardforcel 已提交
68 69
    zip.generateAsync({type: 'nodebuffer', 'compression':'DEFLATE'})
       .then(co => fs.writeFileSync(path, co))
W
init  
wizardforcel 已提交
70 71
}

飞龙 已提交
72
module.exports = writeEpub