Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/adelpro/quran-search-engine/llms.txt

Use this file to discover all available pages before exploring further.

This example demonstrates server-side usage of the Quran Search Engine library in a Node.js environment with a command-line interface.

Features

  • Server-side Quran search
  • Command-line interface
  • Example searches for common Arabic words
  • Search statistics and result display
  • Custom search via command-line arguments
  • Programmatic API usage

Setup

1

Install dependencies

pnpm install
2

Run the example

From the workspace root:
pnpm -C examples/nodejs start
Or from the example directory:
cd examples/nodejs
pnpm start
3

Try custom searches

Provide a search term as an argument:
pnpm -C examples/nodejs start "الله"

Project structure

examples/nodejs/
├── src/
│   └── index.js         # Main script
├── package.json
└── README.md
This example uses JavaScript (not TypeScript) to demonstrate that the library works in standard Node.js environments with ESM.

Main implementation

The complete implementation in a single file:
index.js
import { loadQuranData, loadMorphology, loadWordMap, search } from 'quran-search-engine';

async function main() {
    console.log('🚀 Loading Quran Search Engine data...\n');

    try {
        // Load all required data
        const [quranData, morphologyMap, wordMap] = await Promise.all([
            loadQuranData(),
            loadMorphology(),
            loadWordMap(),
        ]);

        console.log(`✅ Loaded ${quranData.length} verses`);
        console.log(`✅ Loaded morphology data for ${morphologyMap.size} verses`);
        console.log(`✅ Loaded word map with ${Object.keys(wordMap).length} entries\n`);

        // Example searches...
    } catch (error) {
        console.error('❌ Error:', error.message);
        process.exit(1);
    }
}

main();

Loading data

Load all datasets in parallel for optimal performance:
index.js
const [quranData, morphologyMap, wordMap] = await Promise.all([
    loadQuranData(),
    loadMorphology(),
    loadWordMap(),
]);

console.log(`✅ Loaded ${quranData.length} verses`);
console.log(`✅ Loaded morphology data for ${morphologyMap.size} verses`);
console.log(`✅ Loaded word map with ${Object.keys(wordMap).length} entries`);
Loading data in parallel using Promise.all() is faster than loading sequentially.

Example searches

Run predefined example searches:
index.js
const examples = [
    { query: 'الله', description: 'Search for "Allah"' },
    { query: 'رحم', description: 'Search for root "رحم" (mercy)' },
    { query: 'كتب', description: 'Search for "kataba" (wrote)' },
];

for (const example of examples) {
    console.log(`🔍 ${example.description}: "${example.query}"`);
    console.log('─'.repeat(50));

    const results = search(
        example.query,
        quranData,
        morphologyMap,
        wordMap,
        {
            lemma: true,
            root: true,
            fuzzy: true,
        },
        {
            page: 1,
            limit: 5, // Show only first 5 results
        },
    );

    console.log(`📊 Found ${results.pagination.totalResults} matches`);
    console.log(`   - Exact: ${results.counts.simple}`);
    console.log(`   - Lemma: ${results.counts.lemma}`);
    console.log(`   - Root: ${results.counts.root}`);
    console.log(`   - Fuzzy: ${results.counts.fuzzy}\n`);

    // Display results...
}

Displaying results

Format and display search results:
index.js
results.results.forEach((verse, index) => {
    console.log(`${index + 1}. ${verse.sura_name} (${verse.sura_id}:${verse.aya_id})`);
    console.log(`   Match: ${verse.matchType} (Score: ${verse.matchScore})`);
    console.log(`   Text: ${verse.uthmani}`);
    console.log();
});

Custom search via arguments

Accept search terms from command-line arguments:
index.js
// Interactive search if arguments provided
const queryArg = process.argv[2];
if (queryArg) {
    console.log(`🔍 Custom search: "${queryArg}"`);
    console.log('─'.repeat(50));

    const customResults = search(
        queryArg,
        quranData,
        morphologyMap,
        wordMap,
        {
            lemma: true,
            root: true,
            fuzzy: true,
        },
        {
            page: 1,
            limit: 10,
        },
    );

    console.log(`📊 Found ${customResults.pagination.totalResults} matches\n`);

    customResults.results.forEach((verse, index) => {
        console.log(`${index + 1}. ${verse.sura_name} (${verse.sura_id}:${verse.aya_id})`);
        console.log(`   ${verse.uthmani}`);
        console.log();
    });
} else {
    console.log('💡 Tip: Run with a search term as argument:');
    console.log('   pnpm start "your search term"');
}

Error handling

Handle errors and unhandled rejections:
index.js
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection at:', promise, 'reason:', reason);
    process.exit(1);
});

Example output

When you run the script, you’ll see output like this:
🚀 Loading Quran Search Engine data...

 Loaded 6236 verses
 Loaded morphology data for 6236 verses
 Loaded word map with 77403 entries

🔍 Search for "Allah": "الله"
──────────────────────────────────────────────────
📊 Found 2568 matches
   - Exact: 2568
   - Lemma: 0
   - Root: 0
   - Fuzzy: 0

1. Al-Fatiha (1:1)
   Match: exact (Score: 3)
   Text: بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ

2. Al-Fatiha (1:2)
   Match: exact (Score: 3)
   Text: ٱلْحَمْدُ لِلَّهِ رَبِّ ٱلْعَٰلَمِينَ

Dependencies

Minimal dependencies for Node.js usage:
package.json
{
  "name": "nodejs-example",
  "type": "module",
  "scripts": {
    "start": "node src/index.js",
    "dev": "node --watch src/index.js"
  },
  "dependencies": {
    "quran-search-engine": "workspace:*"
  }
}
The "type": "module" field enables ES modules in Node.js, allowing you to use import statements.

Development mode

Run in watch mode for development:
pnpm -C examples/nodejs dev
This uses Node.js’s built-in --watch flag to automatically restart when files change.

Key features demonstrated

  • Server-side usage: Running the library in Node.js without a browser
  • ESM support: Using modern JavaScript modules
  • CLI integration: Processing command-line arguments
  • Batch processing: Running multiple searches programmatically
  • Statistics: Displaying match counts and scores
  • Error handling: Proper error management in async code
  • Simple API: Clean, straightforward implementation

Use cases

  • API backends: Building REST APIs for Quran search
  • Data processing: Batch analysis of Quranic text
  • CLI tools: Command-line utilities for scholars
  • Testing: Automated testing of search functionality
  • Scripts: One-off analysis or data extraction tasks

Build docs developers (and LLMs) love