Created
October 6, 2016 06:07
-
-
Save Tahseenm/8a5674309e33bb4b8bb499d14bef73f1 to your computer and use it in GitHub Desktop.
Get Top story from Hacker News using NightmareJs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Nightmare from 'nightmare'; | |
import colors from 'chalk'; | |
import fs from 'fs'; | |
import path from 'path'; | |
import config from './../config.js'; | |
/* ------------------------------------------ *\ | |
Scrape Hacker News | |
\* ------------------------------------------ */ | |
Nightmare(config.nightmare) | |
.goto('https://news.ycombinator.com/') | |
.inject('js', 'lib/jquery.js') | |
.evaluate(getTopStory) | |
.end() | |
.then(outputJsonFile) | |
.then(printStory) | |
.catch(handleError); | |
function getTopStory() { | |
const story = $('.storylink:first').text(); | |
const itemID = $('.storylink:first').attr('href'); | |
const link = `https://news.ycombinator.com/${itemID}`; | |
return { story, link }; | |
} | |
function outputJsonFile(story) { | |
const prettyJSON = JSON.stringify(story, null, '\t'); | |
const stream = fs.createWriteStream("output/hacker_news-top_story.json"); | |
stream.write(prettyJSON); | |
stream.end(); | |
return story; | |
} | |
function printStory(data) { | |
const {yellow, green} = colors; | |
console.log( | |
yellow('TOP STORY\n'), | |
green(data.story) | |
); | |
} | |
function handleError(error) { | |
console.error( | |
colors.red(`Search failed: ${error}`) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment