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 🙏

© 2025 – Pkg Stats / Ryan Hefner

search-algoritm

v1.1.3

Published

Simple and lightweight fuzzy search algoritm for titles and descriptions.

Downloads

452

Readme

# search-algoritm

![npm version](https://img.shields.io/npm/v/search-algoritm.svg)
![npm downloads](https://img.shields.io/npm/dm/search-algoritm.svg)
![license](https://img.shields.io/npm/l/search-algoritm.svg)
[![GitHub Repository](https://img.shields.io/badge/GitHub-Repository-blue?logo=github)](https://github.com/FelixLind1/SearchAlgoritm)

A lightweight Node.js library for **fuzzy searching** arrays of objects.  
It calculates relevance scores based on how well a query matches the `title` and `description` of each item.  

**Features:**

- Fuzzy matching using **Levenshtein distance**  
- **Accent-insensitive** searches (`é → e`)  
- Token-based word matching for partial or multi-word queries  
- Multi-word sequence detection (`"mac pro"` → `"MacBook Pro"`)  
- Weighted scoring: title matches are more important than description  
- Stopword filtering for more relevant results  

---

## Installation

```bash
npm install search-algoritm

Node.js Usage (Server-side)

This library supports two server setups depending on your dataset size and update frequency:

  1. Cached JSON Server – loads JSON into memory once, reloads if the file changes (fast for large datasets).
  2. Dynamic JSON Server – reads JSON from disk on each request (simple, slower for large datasets).

1. Cached JSON Server (server.js)

const express = require('express');
const path = require('path');
const fs = require('fs').promises;
const { searchAlgoritm } = require('search-algoritm');

const app = express();
const PORT = 3000;
const dataPath = path.join(__dirname, 'data.json');

let searchData = [];

// Load data into memory
const loadData = async () => {
  try {
    const rawData = await fs.readFile(dataPath, 'utf-8');
    searchData = JSON.parse(rawData);
    console.log(`[server] Loaded ${searchData.length} items`);
  } catch (err) {
    console.error('[server] Failed to load data.json:', err);
  }
};

loadData();

// Reload cache if file changes
fs.watchFile(dataPath, async () => {
  console.log('[server] data.json changed, reloading cache...');
  await loadData();
});

app.use(express.static(path.join(__dirname, 'Example files')));

app.get('/api/search', async (req, res) => {
  const query = (req.query.q || "").trim();
  if (!query) return res.json({ query, results: [] });

  const results = searchAlgoritm(query, searchData);
  res.json({ query, results });
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

✅ Fast searches using in-memory cache. Ideal for medium to large datasets where performance matters.


2. Dynamic JSON Server (json-server.js)

const express = require('express');
const path = require('path');
const fs = require('fs').promises;
const { searchAlgoritm } = require('search-algoritm');

const app = express();
const PORT = 3000;

app.use(express.static(path.join(__dirname, 'Example files')));
const dataPath = path.join(__dirname, 'data.json');

const loadJson = async (filePath) => {
  try {
    const rawData = await fs.readFile(filePath, 'utf-8');
    return JSON.parse(rawData);
  } catch (err) {
    console.error('Error reading JSON file:', err);
    return [];
  }
};

app.get('/api/search', async (req, res) => {
  const query = req.query.q || "";
  const searchData = await loadJson(dataPath);
  const results = searchAlgoritm(query, searchData);
  res.json({ query, results });
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

✅ Reads JSON on each request. Best for small datasets or when data changes frequently.


Best Practices

| Server Type | Pros | Cons | When to Use | | ------------ | ------------------------------- | ---------------------------------------------- | ------------------------------------------- | | Cached JSON | Fast searches, reduces disk I/O | Uses more memory, needs cache reload on change | Medium to large datasets, frequent searches | | Dynamic JSON | Always fresh data, simple setup | Slower for large datasets | Small datasets or frequently changing data |

Tip: For production with large datasets, use the cached server. For prototypes or rapidly changing content, use the dynamic server.


Frontend Usage (Browser)

Always fetch search results from the server.

ip-adress.js

const backendIP = 'http://localhost:3000';
export default backendIP;

search.js

import backendIP from './ip-adress.js';

async function initSearch() {
  const searchInput = document.getElementById('searchInput');
  const searchBtn = document.getElementById('searchBtn');
  const resultsList = document.getElementById('searchResults');

  async function performSearch() {
    const query = searchInput.value.trim();
    if (!query) {
      resultsList.innerHTML = `<li class="no-result">Please enter a search term</li>`;
      return;
    }

    try {
      const res = await fetch(`${backendIP}/api/search?q=${encodeURIComponent(query)}`);
      const { results } = await res.json();

      resultsList.innerHTML = results.length
        ? results.map(item => `
            <li class="result-item">
              <strong>${item.title}</strong><br>
              <span>${item.description}</span>
            </li>
          `).join('')
        : `<li class="no-result">No matches found</li>`;
    } catch (err) {
      console.error('Error fetching search results:', err);
      resultsList.innerHTML = `<li class="no-result">Could not fetch results</li>`;
    }
  }

  searchInput.addEventListener('keydown', e => { if (e.key === 'Enter') performSearch(); });
  searchBtn.addEventListener('click', performSearch);
}

initSearch();

License

MIT

Made by Felix Lind