当前位置 : 主页 > 网络编程 > JavaScript >

为 HTML 生成 epub 条目(htmlref.js)

来源:互联网 收集:自由互联 发布时间:2021-06-28
htmlref.js var fs = require('fs');var uuidGenerator = require('uuid');var ejs = require('ejs');var dirname = process.argv[2];if(!dirname){ console.log('请指定路径。'); process.exit(0);}var ndDecor = process.argv[3] == 'yes';var dir =
htmlref.js
var fs = require('fs');
var uuidGenerator = require('uuid');
var ejs = require('ejs');

var dirname = process.argv[2];
if(!dirname)
{
    console.log('请指定路径。');
    process.exit(0);
}
var ndDecor = process.argv[3] == 'yes';

var dir = fs.readdirSync(dirname);

var toc = [];

for(var filename of dir) {
    
    if(!filename.endsWith('.html'))
        continue;
    console.log(filename);
    
    var co = fs.readFileSync(dirname + '/' + filename, 'utf-8');
    
    var title = /
 
  \s*(.+?)\s*<\/h1>/m.exec(co)[1];
    toc.push({file: filename, title: title});
    
    if(ndDecor) {
        var header = '\r\n\r\n\r\n' +
            '' +
            '\r\n\r\n';
        var footer = '\r\n\r\n';
        fs.writeFileSync(dirname + '/' + filename, header + co + footer);
    }
}
toc.sort((a, b) => a.file.replace('.html', '') - b.file.replace('.html', ''));

var uuid = uuidGenerator();
fs.writeFileSync(dirname + '/content.opf', getContentOpf(toc, uuid));
fs.writeFileSync(dirname + '/toc.ncx', getTocNcx(toc, uuid));
console.log('done..');

function getContentOpf(toc, uuid)
{
    var date = new Date();
    var dateStr 
        = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
    
    return ejs.render(fs.readFileSync('assets/content.ejs', 'utf-8'), {
        date: dateStr,
        toc: toc,
        uuid: uuid
    });
}

function getTocNcx(toc, uuid)
{
    return ejs.render(fs.readFileSync('assets/toc.ejs', 'utf-8'), {
        toc: toc,
        uuid: uuid
    });
}
 
网友评论