-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
88 lines (74 loc) · 1.76 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*global require, process */
var express = require("express"),
path = require("path"),
fs = require("fs"),
cheerio = require("cheerio"),
request = require("request");
var app = express(),
hn_api = {
base: "https://hacker-news.firebaseio.com/v0/",
top: "topstories.json",
new: "newstories.json"
};
app.use(express.static(path.join(__dirname, "public")));
app.get("/", function (req, res) {
fs.readFile("index.html", function (err, data) {
if (err) {
return;
}
res.send(data.toString());
});
});
app.get("/item", function (req, res) {
var id = req.query.id,
story_url = hn_api.base + "item/" + id + ".json";
request({
uri: story_url
}, function (error, response, body) {
if (error) {
console.error(error);
return;
}
var storyJSON = JSON.parse(body);
// console.log(storyJSON.url)
// res.json(storyJSON);
request({
uri: storyJSON.url
}, function(error, response, body){
try{
var $ = cheerio.load(body);
var fbDescription = $("meta[property=\"og:description\"]");
storyJSON.description = $(fbDescription).attr("content");
var fbImage = $("meta[property=\"og:image\"]");
// var firstImg = $("img").get(0);
storyJSON.image = $(fbImage).attr("content");// || $(firstImg).attr("src");
res.json(storyJSON);
} catch(err){
console.error(err);
}
});
});
});
app.get("/top", function (req, res) {
request({
uri: hn_api.base + hn_api.top
}, function (error, response, body) {
if (error) {
console.error(error);
return;
}
res.jsonp(body);
});
});
app.get("/new", function (req, res) {
request({
uri: hn_api.base + hn_api.new
}, function (error, response, body) {
if (error) {
console.error(error);
return;
}
res.jsonp(body);
});
});
app.listen(Number(process.argv[2]));