Skip to content

Instantly share code, notes, and snippets.

@davidar
Created November 10, 2016 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidar/0eeb0fce942e4ea1b1dafee2e3d8a801 to your computer and use it in GitHub Desktop.
Save davidar/0eeb0fce942e4ea1b1dafee2e3d8a801 to your computer and use it in GitHub Desktop.
var jsdom = require("jsdom").jsdom;
var Readability = require("./index").Readability;
var express = require("express");
var app = express();
function removeCommentNodesRecursively(node) {
for (var i = node.childNodes.length - 1; i >= 0; i--) {
var child = node.childNodes[i];
if (child.nodeType === child.COMMENT_NODE) {
node.removeChild(child);
} else if (child.nodeType === child.ELEMENT_NODE) {
removeCommentNodesRecursively(child);
}
}
}
app.get(/^\/(.+)$/, function (req, res) {
var url = req.params[0];
jsdom.env(url, [], function (err, window) {
if (err) {
console.error(err);
} else {
var document = window.document;
removeCommentNodesRecursively(document);
var loc = document.location;
var uri = {
spec: loc.href,
host: loc.host,
prePath: loc.protocol + "//" + loc.host,
scheme: loc.protocol.substr(0, loc.protocol.indexOf(":")),
pathBase: loc.protocol + "//" + loc.host + loc.pathname.substr(0, loc.pathname.lastIndexOf("/") + 1)
};
var article = new Readability(uri, document).parse();
if (article) {
var html = '<!DOCTYPE html><html><head>';
html += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';
html += '<title>' + article.title + '</title>';
html += '<meta name="viewport" content="width=device-width, initial-scale=1">';
html += '<link rel="stylesheet" href="https://texify.davidar.io/main.css" type="text/css">';
html += '<link rel="canonical" href="' + url + '">';
html += '</head><body><header><h1>' + article.title.replace(/ (-|\|) .*/, '') + '</h1>';
if (article.byline) {
html += '<address>' + article.byline + '</address>';
}
html += '</header><main>' + article.content + '</main>';
html += '<script async src="https://texify.davidar.io/load.js"></script></body></html>';
res.send(html);
} else {
res.redirect(url);
}
}
});
});
var port = process.env.PORT || 4313;
app.listen(port, function() {
console.log("Listening on port " + port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment