Back to Home
Gistify Snippet
Public
Scraper berita - Hacker News
Scraper berita - Hacker News
#github-gist#javascript#gist:7759bcb32b8650d59e283c7bc8aabec5#gistsync:2026-09-02T10:46:03Z
2
Rawnews.jsjavascript
53 lines| 1 | import axios from 'axios'; |
| 2 | |
| 3 | const COUNTRY = "id"; |
| 4 | const CATEGORY = ""; |
| 5 | const PAGE_SIZE = 5; |
| 6 | |
| 7 | export async function getNews(country, category, pageSize) { |
| 8 | |
| 9 | try { |
| 10 | const res = await fetch(`https://hacker-news.firebaseio.com/v0/topstories.json`); |
| 11 | const ids = await res.json(); |
| 12 | |
| 13 | const stories = await Promise.all( |
| 14 | ids.slice(0, pageSize).map(async (id) => { |
| 15 | const r = await fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`); |
| 16 | const s = await r.json(); |
| 17 | return { |
| 18 | id: s.id, |
| 19 | title: s.title, |
| 20 | url: s.url || `https://news.ycombinator.com/item?id=${s.id}`, |
| 21 | score: s.score, |
| 22 | by: s.by, |
| 23 | time: new Date(s.time * 1000).toISOString(), |
| 24 | comments: s.descendants || 0, |
| 25 | type: s.type |
| 26 | }; |
| 27 | }) |
| 28 | ); |
| 29 | |
| 30 | return { status: true, source: "Hacker News", country: country || "top", category: category || "top", total: stories.length, stories }; |
| 31 | } catch (err) { |
| 32 | throw new Error(err.message || "Gagal mengambil berita."); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | const __is_main = (() => { |
| 37 | try { |
| 38 | if (!process.argv[1]) return false; |
| 39 | return import.meta.url.endsWith(process.argv[1].replace(/\\/g, '/')); |
| 40 | } catch (_) { return false; } |
| 41 | })(); |
| 42 | |
| 43 | if (__is_main) { |
| 44 | (async () => { |
| 45 | try { |
| 46 | const result = await getNews(COUNTRY, CATEGORY, PAGE_SIZE); |
| 47 | console.log(JSON.stringify(result, null, 2)); |
| 48 | } catch (e) { |
| 49 | console.error('Error: ' + e.message); |
| 50 | process.exitCode = 1; |
| 51 | } |
| 52 | })(); |
| 53 | } |
Discussion & Comments0
No comments yet — be the first to leave feedback or start a code discussion.
Sign in with your GitHub account to write comments and join the discussion.