npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

h56-wikipedia-scrapper

v1.0.4

Published

Professional, modular and ESM-first Wikipedia data fetcher (uses official Wikipedia API).

Readme

h56-wikipedia-scrapper

Profesional, modular, dan ESM-first utility untuk mengambil (fetch) data terstruktur dari Wikipedia menggunakan API resmi. Paket ini didesain untuk developer yang butuh hasil stabil, aman, dan mudah diintegrasikan ke aplikasi Node.js modern.

  • ESM-native (ditulis untuk Node.js >=16+, type: "module")
  • Menggunakan Wikipedia API resmi (action=query & action=parse) — TOS-friendly
  • Output konsisten dalam JSON terstruktur
  • Async/Await, Promise-based
  • In-memory cache opsional + kontrol concurrency
  • Typings TypeScript (type.d.ts) disertakan

Table of Contents


Requirements

  • Node.js >= 16 (direkomendasikan LTS terbaru)
  • NPM / Yarn
  • Paket otomatis terpasang melalui npm install:
    • axios
    • cheerio

Note: Anda tidak perlu memasang dependency secara manual; npm install h56-wikipedia-scrapper akan meng-install dependencies yang diperlukan.


Install

NPM:

npm install h56-wikipedia-scrapper

Yarn:

yarn add h56-wikipedia-scrapper

Quick Start (ESM)

Contoh penggunaan ESM (direkomendasikan):

import { search, searchOne, fetchOverview } from 'h56-wikipedia-scrapper';

async function main() {
  try {
    // Mencari 1 hasil teratas
    const top = await searchOne('Node.js', { lang: 'en', timeout: 8000 });
    console.log('Top result:', top);

    // Mengambil ringkasan terstruktur (title, description, published date, image url, url)
    const overview = await fetchOverview('Node.js', { lang: 'en' });
    console.log('Overview:', overview);

    // Mencari 3 hasil teratas
    const results = await search('JavaScript', { lang: 'en', maxResults: 3 });
    console.log('Results:', results);
  } catch (err) {
    console.error('Error:', err?.code ?? 'UNKNOWN', err?.message ?? err);
  }
}

main();

Integration helper: fetchOverview

fetchOverview(keyword, options) adalah helper yang berguna ketika Anda hanya membutuhkan ringkasan singkat:

  • title: judul halaman
  • description: ringkasan teks (extract)
  • published: tanggal pertama halaman ditemukan di Wikipedia (first revision timestamp) bila tersedia; fallback ke lastEdited jika tidak tersedia
  • image: primary image URL (jika ada)
  • url: canonical Wikipedia URL

Kegunaan: menampilkan preview artikel, meta info di UI, atau menyimpan ringkasan singkat ke DB tanpa perlu parsing HTML manual.


Using from CommonJS

Paket ini ESM-first. Jika proyek Anda masih CommonJS (require), gunakan dynamic import (runtime) atau jalankan modul ESM via bundler.

Contoh CommonJS runtime using dynamic import:

// example-cjs.js
(async () => {
  try {
    const mod = await import('h56-wikipedia-scrapper');
    // modul meng-export named exports dan default
    const { fetchOverview } = mod;
    const overview = await fetchOverview('Python (programming language)');
    console.log(overview);
  } catch (err) {
    console.error(err);
  }
})();

TypeScript Usage

Typings disertakan (type.d.ts). Contoh file .ts:

import { search, searchOne, fetchOverview, SearchOptions, WikiResult } from 'h56-wikipedia-scrapper';

async function example() {
  const opts: SearchOptions = { lang: 'en', maxResults: 2, cacheTTL: 60_000 };
  const results: WikiResult[] = await search('Node.js', opts);
  console.log(results[0].title);

  const overview = await fetchOverview('Node.js', opts);
  console.log('Title:', overview?.title);
  console.log('Published:', overview?.published);
  console.log('Image URL:', overview?.image);
}

example().catch(console.error);

API Reference

search(keyword: string, opts?: SearchOptions): Promise<WikiResult[]>

  • Menjalankan pencarian pada Wikipedia (bahasa sesuai opts.lang) dan mengembalikan hingga opts.maxResults objek hasil dalam bentuk array.
  • Input keyword harus string non-empty.
  • Mengembalikan array hasil berurutan sesuai ranking Wikipedia.

searchOne(keyword: string, opts?: SearchOptions): Promise<WikiResult | null>

  • Helper yang memanggil search dengan maxResults: 1 dan mengembalikan hasil pertama atau null jika tidak ditemukan.

fetchOverview(keyword: string, opts?: SearchOptions): Promise<{title, description, published, image, url} | null>

  • Helper ringkasan yang mengembalikan objek dengan fields: title, description, published, image, url.
  • published adalah timestamp ISO dari firstPublished revision jika tersedia, atau lastEdited jika tidak tersedia.

SearchOptions

Properti penting:

  • lang?: string — kode bahasa Wikipedia (default: 'en')
  • timeout?: number — ms timeout untuk HTTP (default: 8000)
  • maxResults?: number — jumlah hasil maksimum (default: 1)
  • useCache?: boolean — aktifkan cache (default: true)
  • cacheTTL?: number — TTL cache dalam ms (default: 300000)
  • parseConcurrency?: number — limit concurrency untuk action=parse (default: 2)

WikiResult (contoh struktur output)

Setiap elemen array hasil memiliki format:

  • pageId: number
  • title: string
  • displayTitle: string
  • summary: string (plain-text extract)
  • paragraphs: string[] (paragraph utama yang diambil dari HTML parse; jika parse gagal, fallback ke summary)
  • url: string (canonical Wikipedia URL)
  • mainImage: { source: string, width?: number, height?: number } | null
  • lastEdited: string | null (ISO timestamp)
  • firstPublished: string | null (ISO timestamp dari revision pertama, bila tersedia)
  • metadata: { length?: number, ns?: number, categories?: string[] }

Examples

1) Basic search

import { searchOne } from 'h56-wikipedia-scrapper';

(async () => {
  const result = await searchOne('Daffodil', { lang: 'en' });
  console.log(result?.title, result?.url);
})();

2) Mendapatkan ringkasan (title, description, published, image)

import { fetchOverview } from 'h56-wikipedia-scrapper';

(async () => {
  const overview = await fetchOverview('Node.js', { lang: 'en' });
  if (overview) {
    console.log('Title:', overview.title);
    console.log('Description:', overview.description);
    console.log('Published (first revision):', overview.published);
    console.log('Image URL:', overview.image);
    console.log('Page URL:', overview.url);
  } else {
    console.log('No overview found.');
  }
})();

3) Top 3 results dan custom timeout

import { search } from 'h56-wikipedia-scrapper';

(async () => {
  const results = await search('Apollo', { lang: 'en', maxResults: 3, timeout: 12000 });
  results.forEach(r => console.log(r.title, '-', r.url));
})();

4) Menangani error & fallback behavior

import { search } from 'h56-wikipedia-scrapper';

try {
  const results = await search('', { lang: 'en' }); // invalid input
} catch (err) {
  if (err.code === 'INVALID_INPUT') {
    console.error('Masukkan kata kunci pencarian yang valid.');
  } else {
    console.error('Kesalahan lain:', err.code, err.message);
  }
}

Advanced Options & Tuning

  • cacheTTL: sesuaikan berdasarkan kebutuhan frekuensi permintaan. TTL rendah (mis. 60s) cocok untuk data yang sering berubah; TTL tinggi cocok untuk mengurangi beban pada API.
  • useCache: non-aktifkan cache jika Anda selalu membutuhkan data segar.
  • parseConcurrency: jika Anda memanggil banyak halaman sekaligus, turunkan nilai ini agar tidak membanjiri endpoint action=parse. Default 2; tingkatkan jika Anda dapat menjamin rate-limit/etika.
  • timeout: perlu disesuaikan di lingkungan lambat; default 8000ms.

Catatan: implementasi saat ini menggunakan in-memory Map — untuk infra production skala besar, pertimbangkan cache eksternal (Redis, Memcached) dan retry/backoff logic eksternal.


Best Practices & Compliance

  • Paket menggunakan API resmi Wikipedia (w/api.php) untuk tetap sesuai Terms of Service. Hindari crawling HTML langsung secara massal.
  • Batasi frekuensi permintaan (throttling) jika melakukan banyak pencarian otomatis.
  • Gunakan parseConcurrency rendah dan cache untuk mengurangi beban ke server Wikipedia.
  • Sertakan User-Agent khas (sudah diatur oleh paket) yang memberi identitas agent untuk Wikipedia.

Troubleshooting

  • "Request timed out" — tingkatkan timeout atau pastikan koneksi jaringan baik.
  • "No Wikipedia results found" — periksa kata kunci yang dipakai, atau gunakan query yang lebih spesifik.
  • Error WIKI_API_ERROR — periksa apakah Wikipedia API tersedia untuk bahasa lang yang dipilih (mis. id.wikipedia.org).
  • Jika Anda menggunakan CommonJS dan mendapat error import — gunakan dynamic import seperti contoh di atas atau migrasikan proyek ke ESM.

Contributing

Kontribusi diterima (issues, PR). Pedoman singkat:

  1. Fork repository
  2. Buat branch fitur (feat/xyz) atau perbaikan (fix/abc)
  3. Tambahkan test (direkomendasikan) dan dokumentasi jika perlu
  4. Ajukan PR dengan deskripsi perubahan dan alasan

Silakan ikuti praktik umum Open Source: tes, linting, dan backward-compatibility.


License

MIT