Socket
Book a DemoInstallSign in
Socket

hadith

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

hadith

Searching and browsing hadith collections with Arabic and English support

1.3.0
latest
Source
npmnpm
Version published
Maintainers
1
Created
Source

Hadith

A comprehensive npm package for searching and browsing hadith collections with Arabic and English support. This package provides easy access to 16 major authentic hadith collections including Sahih al-Bukhari, Sahih Muslim, Sunan an-Nasa'i, and many more.

Features both a powerful library API and an interactive CLI tool for different use cases - whether you're building applications or studying hadiths directly in the terminal.

Features

📚 16 Major Collections

Includes all the essential hadith collections: Sahih al-Bukhari, Sahih Muslim, the six canonical collections (Kutub al-Sittah), Musnad Ahmad, Riyad as-Salihin, and more.

🛠️ Dual Interface

  • 📦 Library API: Use as an npm package in your applications
  • ⚡ CLI Tool: Interactive terminal interface for browsing and studying
  • Full-text search in both Arabic and English
  • Search across all collections or filter by specific collection
  • Support for Arabic text with and without diacritics

🌐 Multilingual Support

  • Original Arabic text with proper handling of diacritics
  • English translations for nearly all hadiths (99.97% coverage)
  • Narrator information in both languages

📊 Rich Metadata

  • Collection statistics and metadata
  • Book and chapter organization
  • Hadith grading and authentication information
  • Scholar information and references

💾 Offline First

  • Works completely offline with embedded SQLite database
  • No internet connection required
  • Fast local queries and navigation

🔧 Developer Friendly

  • Full TypeScript support with type definitions
  • Promise-based async API
  • Comprehensive error handling
  • Extensive documentation and examples

Installation

npm install hadith

Using the CLI Tool

The package includes a hadith-cli binary for interactive terminal usage:

# If installed locally
npx hadith-cli

# Run the CLI directly
node node_modules/hadith/cli.js

# Or install globally for the hadith-cli command
npm install -g hadith
hadith-cli

Requirements

  • Node.js >= 14.0.0
  • The package includes the hadith database (data/hadith.db)

Quick Start

const HadithDB = require('hadith');

async function example() {
  // Initialize the database
  const hadithDb = new HadithDB();
  await hadithDb.connect();

  try {
    // Get all collections (16 available)
    const collections = await hadithDb.getCollections();
    console.log(`Available collections: ${collections.length}`);

    // Search for hadiths about prayer
    const searchResults = await hadithDb.search('prayer');
    console.log(`Found ${searchResults.total} hadiths about prayer`);

    // Get a random hadith
    const randomHadith = await hadithDb.getRandomHadith();
    console.log('Random hadith:', randomHadith.content);

    // Get collection statistics
    const stats = await hadithDb.getCollectionStats();
    console.log(`Total hadiths: ${stats.total_hadiths}`);

  } finally {
    // Always close the connection
    await hadithDb.close();
  }
}

example().catch(console.error);

⚡ Interactive CLI Tool

The package includes a powerful interactive CLI for browsing and studying hadiths directly in the terminal.

CLI Features

  • 🌙 Hierarchical Navigation: Collections → Books → Chapters → Hadiths
  • 🔍 Autocomplete Search: Type-ahead search for easy navigation
  • 🌐 Bilingual Display: Arabic text with English translations
  • 🎲 Random Hadith: Get random hadiths for daily reading
  • Fast Navigation: Quick back navigation between levels
  • 📜 Rich Display: Formatted hadith display with metadata
  • 📤 Export Options: Export collections and books as JSON

Using the CLI

# Run directly from the package
node node_modules/hadith/cli.js

# Or if installed globally
hadith-cli

CLI Navigation Flow

  • Select Collection: Choose from 16 available hadith collections
  • Select Book: Browse books within the selected collection
  • Select Chapter: View chapters within the selected book (or skip to view all hadiths)
  • Select Hadith: Choose individual hadiths to read
  • View Hadith: Full display with Arabic text, English translation, and metadata

Example CLI Session

🌙 Welcome to Hadith CLI
═══════════════════════════════════════

? 📚 Select a hadith collection: Sahih al-Bukhari | صحيح البخاري

📖 Books in Sahih al-Bukhari:
──────────────────────────────────────────────────

? 📖 Select a book: Book 1: Revelation | كتاب بدء الوحى

📜 Hadiths displayed with full Arabic text, English translation,
narrator information, and metadata...

📦 Library API Documentation

Constructor

new HadithDB(dbPath?)

Creates a new HadithDB instance.

  • dbPath (optional): Path to the SQLite database file. Defaults to the embedded database
const hadithDb = new HadithDB();
// or with custom path
const hadithDb = new HadithDB('/path/to/hadith.db');

Collection Methods

getCollections(): Collection[]

Returns all hadith collections.

const collections = hadithDb.getCollections();
collections.forEach(collection => {
  console.log(`${collection.title_en} (${collection.title})`);
});

getCollection(collectionId): Collection | null

Get a specific collection by ID.

const bukhari = hadithDb.getCollection(1); // Sahih al-Bukhari
console.log(bukhari.title_en); // "Sahih al-Bukhari"

getCollectionStats(collectionId?): CollectionStats

Get statistics for a collection or overall database.

// Overall stats
const stats = hadithDb.getCollectionStats();
console.log(`Total collections: ${stats.collection_count}`);

// Collection-specific stats
const bukhariStats = hadithDb.getCollectionStats(1);
console.log(`Books in Bukhari: ${bukhariStats.book_count}`);

Book Methods

getBooks(collectionId): Book[]

Get all books in a collection.

const books = hadithDb.getBooks(1); // Books in Sahih al-Bukhari
books.forEach(book => {
  console.log(`${book.title_en} (${book.hadith_count} hadiths)`);
});

getBook(collectionId, bookId): Book | null

Get a specific book.

const book = hadithDb.getBook(1, 1); // First book of Bukhari
console.log(book.title_en); // "Revelation"

Chapter Methods

getChapters(collectionId, bookId): Chapter[]

Get all chapters in a book.

const chapters = hadithDb.getChapters(1, 1); // Chapters in first book
chapters.forEach(chapter => {
  console.log(chapter.title_en);
});

getChapter(collectionId, bookId, chapterId): Chapter | null

Get a specific chapter.

const chapter = hadithDb.getChapter(1, 1, 1);
console.log(chapter.title_en);

Hadith Retrieval Methods

getHadithsByCollection(collectionId, options?): Hadith[]

Get hadiths from a collection with optional filtering.

// Get first 10 hadiths from Bukhari
const hadiths = hadithDb.getHadithsByCollection(1, { limit: 10 });

// Get hadiths from specific book
const bookHadiths = hadithDb.getHadithsByCollection(1, { 
  bookId: 1, 
  limit: 5 
});

// Get hadiths from specific chapter
const chapterHadiths = hadithDb.getHadithsByCollection(1, {
  bookId: 1,
  chapterId: 1,
  limit: 3
});

getEnglishHadithsByCollection(collectionId, options?): EnglishHadith[]

Get English translations of hadiths.

const englishHadiths = hadithDb.getEnglishHadithsByCollection(1, { limit: 10 });
englishHadiths.forEach(hadith => {
  console.log(hadith.content);
});

getHadithByUrn(urn): Hadith | null

Get a specific hadith by its URN (Uniform Resource Name).

const hadith = hadithDb.getHadithByUrn('bukhari:1:1:1');
if (hadith) {
  console.log(hadith.content);
}

getEnglishHadithByUrn(urn): EnglishHadith | null

Get English translation of a hadith by URN.

const englishHadith = hadithDb.getEnglishHadithByUrn('bukhari:1:1:1');
if (englishHadith) {
  console.log(englishHadith.content);
}

getHadithByNumber(number): Hadith | null

Search for a hadith by number across all collections. This method tries three search strategies in order:

  • order_in_book - Sequential position within a collection
  • display_number - Hadith number within a book
  • collection_id - Returns first hadith from that collection (if number ≤ 16)
// Find hadith 6689 (famous intentions hadith)
const hadith = await hadithDb.getHadithByNumber(6689);
if (hadith) {
  console.log(`Found by: ${hadith.found_by}`); // "order_in_book"
  console.log(`Collection: ${hadith.collection_id}`); // 1 (Al-Bukhari)
  console.log(`Content: ${hadith.content}`);
}

// Search by display number
const hadith23 = await hadithDb.getHadithByNumber(23);
if (hadith23) {
  console.log(`Found by: ${hadith23.found_by}`); // "display_number" or "order_in_book"
}

// Get first hadith from collection 2 (Sahih Muslim)
const muslimHadith = await hadithDb.getHadithByNumber(2);
if (muslimHadith) {
  console.log(`Found by: ${muslimHadith.found_by}`); // "order_in_book" or "collection_id"
}

Note: The found_by field indicates which search method succeeded. Since order_in_book numbers are not globally unique across collections, this method returns the first match found.

Search Methods

searchArabic(query, options?): Hadith[]

Search hadiths in Arabic.

// Basic search
const results = hadithDb.searchArabic('الصلاة');

// Search with options
const results = hadithDb.searchArabic('الصلاة', {
  collectionId: 1, // Only in Bukhari
  limit: 20,
  searchInDiacless: true // Search without diacritics
});

searchEnglish(query, options?): EnglishHadith[]

Search hadiths in English.

const results = hadithDb.searchEnglish('prayer', {
  collectionId: 1,
  limit: 10
});

search(query, options?): SearchResults

Search in both Arabic and English.

const results = hadithDb.search('prayer');
console.log(`Arabic results: ${results.arabic.length}`);
console.log(`English results: ${results.english.length}`);
console.log(`Total: ${results.total}`);

Utility Methods

getRandomHadith(collectionId?): Hadith | null

Get a random hadith.

// Random hadith from any collection
const randomHadith = hadithDb.getRandomHadith();

// Random hadith from specific collection
const randomBukhari = hadithDb.getRandomHadith(1);

getScholars(): Scholar[]

Get information about hadith scholars.

const scholars = hadithDb.getScholars();
scholars.forEach(scholar => {
  console.log(`${scholar.famous_name} (${scholar.born_on} - ${scholar.died_on})`);
});

getInfo(): DatabaseInfo

Get database information and statistics.

const info = hadithDb.getInfo();
console.log(`Database version: ${info.version}`);
console.log(`Available collections: ${info.collections.length}`);

close(): void

Close the database connection.

hadithDb.close(); // Always close when done

Examples

Search Example

const HadithDB = require('hadith');
const hadithDb = new HadithDB();

// Search for hadiths about charity
const results = hadithDb.search('charity');

console.log(`Found ${results.total} hadiths about charity:`);
console.log(`- ${results.arabic.length} in Arabic`);
console.log(`- ${results.english.length} in English`);

// Display first English result
if (results.english.length > 0) {
  const hadith = results.english[0];
  console.log(`\nHadith: ${hadith.content}`);
  console.log(`Reference: ${hadith.reference}`);
}

hadithDb.close();

Browse Collections Example

const HadithDB = require('hadith');
const hadithDb = new HadithDB();

// Get all collections
const collections = hadithDb.getCollections();

collections.forEach(collection => {
  console.log(`\n${collection.title_en} (${collection.title})`);
  console.log(`Status: ${collection.status}`);
  
  // Get books in this collection
  const books = hadithDb.getBooks(collection.id);
  console.log(`Books: ${books.length}`);
  
  // Get first few hadiths
  const hadiths = hadithDb.getHadithsByCollection(collection.id, { limit: 3 });
  console.log(`Sample hadiths: ${hadiths.length}`);
});

hadithDb.close();

Daily Hadith Example

const HadithDB = require('hadith');
const hadithDb = new HadithDB();

function getDailyHadith() {
  const hadith = hadithDb.getRandomHadith();
  const englishHadith = hadithDb.getEnglishHadithByUrn(hadith.urn);
  
  return {
    arabic: hadith.content,
    english: englishHadith ? englishHadith.content : null,
    reference: hadith.urn,
    narrator: hadith.narrator_prefix
  };
}

const daily = getDailyHadith();
console.log('Today\'s Hadith:');
console.log(`Arabic: ${daily.arabic}`);
if (daily.english) {
  console.log(`English: ${daily.english}`);
}
console.log(`Reference: ${daily.reference}`);

hadithDb.close();

Find Specific Hadith by Number Example

const HadithDB = require('hadith');
const hadithDb = new HadithDB();

async function findSpecificHadith() {
  // Find the famous intentions hadith (#6689)
  const hadith = await hadithDb.getHadithByNumber(6689);
  
  if (hadith) {
    console.log(`Found by: ${hadith.found_by}`); // "order_in_book"
    console.log(`URN: ${hadith.urn}`);
    console.log(`Collection: ${hadith.collection_id}`); // 1 (Al-Bukhari)
    
    // Get collection and book information
    const collection = await hadithDb.getCollection(hadith.collection_id);
    const book = await hadithDb.getBook(hadith.collection_id, hadith.book_id);
    
    console.log(`\nCollection: ${collection.title_en}`);
    console.log(`Book: ${book.title_en}`);
    console.log(`Hadith #${hadith.display_number} in ${book.title_en}`);
    
    console.log(`\nArabic: ${hadith.content}`);
    
    // Get English translation
    const englishHadith = await hadithDb.getEnglishHadithByUrn(hadith.urn);
    if (englishHadith) {
      console.log(`\nEnglish: ${englishHadith.content}`);
      console.log(`Reference: ${englishHadith.reference}`);
    }
  } else {
    console.log('Hadith not found');
  }
}

findSpecificHadith()
  .then(() => hadithDb.close())
  .catch(console.error);

TypeScript Support

The package includes full TypeScript definitions:

import HadithDB, { Collection, Hadith, SearchResults } from 'hadith';

const hadithDb = new HadithDB();

const collections: Collection[] = hadithDb.getCollections();
const results: SearchResults = hadithDb.search('prayer');
const hadith: Hadith | null = hadithDb.getRandomHadith();
const specificHadith: Hadith | null = await hadithDb.getHadithByNumber(6689);

hadithDb.close();

📚 Available Collections (16 Total)

The database includes 16 major authentic hadith collections with nearly complete English translations:

The Six Canonical Collections (Kutub al-Sittah)

  • Sahih al-Bukhari (صحيح البخاري) - 7,277 hadiths in 97 books
  • Sahih Muslim (صحيح مسلم) - 7,368 hadiths in 56 books
  • Sunan an-Nasa'i (سنن النسائي) - 5,768 hadiths in 52 books
  • Sunan Abi Dawud (سنن أبي داود) - 5,276 hadiths in 43 books
  • Jamiʿ at-Tirmidhi (جامع الترمذي) - 4,053 hadiths in 49 books
  • Sunan Ibn Majah (سنن ابن ماجه) - 4,345 hadiths in 38 books

Other Major Collections

  • Muwatta Malik (موطأ مالك) - 1,861 hadiths in 61 books
  • Musnad Ahmad (مسند أحمد) - 4,346 hadiths in 26 books
  • Riyad as-Salihin (رياض الصالحين) - 1,896 hadiths in 20 books
  • Mishkat al-Masabih (مشكاة المصابيح) - 4,433 hadiths in 25 books
  • Al-Adab Al-Mufrad (الأدب المفرد) - 1,326 hadiths in 57 books
  • Bulugh al-Maram (بلوغ المرام) - 1,767 hadiths in 16 books

Specialized Collections

  • An-Nawawi's 40 Hadith (الأربعون النووية) - The famous 40 essential hadiths
  • Collections of Forty (الأربعينات) - 122 hadiths in 3 books
  • Ash-Shama'il Al-Muhammadiyah (الشمائل المحمدية) - 402 hadiths about the Prophet's character
  • Hisn al-Muslim (حصن المسلم) - 268 supplications and prayers

Coverage Statistics

  • Total Arabic Hadiths: 50,508
  • Total English Translations: 50,495
  • Overall Translation Coverage: 99.97%
  • Complete Collections: 15 out of 16 have 100% English coverage

Use getCollections() to programmatically access all collection metadata.

Performance Notes

  • The package uses SQLite with WAL mode for better performance
  • Search operations use SQL LIKE queries for compatibility
  • For better search performance with the full FTS capabilities, ensure your SQLite installation supports the Arabic tokenizer
  • Always call close() when done to free resources

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see LICENSE file for details.

Support

For questions and support, please open an issue on GitHub.

Keywords

hadith

FAQs

Package last updated on 20 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.