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

emotion-detector-js

v1.0.2

Published

A simple JavaScript/TypeScript client for the Emotion Tone Analyzer API - works in Node.js and browsers

Downloads

7

Readme

emotion-detector-js

A simple JavaScript/TypeScript client for the Emotion Tone Analyzer API. Works seamlessly in Node.js and browser environments with zero dependencies.

🚀 Live Demo

Features

  • 🎯 Simple API - Easy to use analyze() and analyzeBatch() methods
  • 📦 Zero Dependencies - Uses native fetch API
  • 🔷 TypeScript Support - Full type definitions included
  • 🌐 Universal - Works in Node.js (18+) and browsers
  • Dual Module - ESM and CommonJS support
  • 🛡️ Built-in Validation - Automatic word count validation before API calls
  • 🔧 Configurable - Custom base URL for self-hosted instances

Installation

npm install emotion-detector-js
yarn add emotion-detector-js
pnpm add emotion-detector-js

Quick Start

import { EmotionAnalyzer } from 'emotion-detector-js';

const analyzer = new EmotionAnalyzer();

// Analyze a single text
const result = await analyzer.analyze("I'm so happy today!");
console.log(result.primaryEmotion); // "joy"
console.log(result.confidence);     // 0.95

Usage

Single Text Analysis

import { EmotionAnalyzer } from 'emotion-detector-js';

const analyzer = new EmotionAnalyzer();

const result = await analyzer.analyze("I'm feeling great about this project!");

console.log(result);
// {
//   primaryEmotion: "joy",
//   confidence: 0.92,
//   allEmotions: [
//     { emotion: "joy", score: 0.92 },
//     { emotion: "surprise", score: 0.05 },
//     { emotion: "neutral", score: 0.03 }
//   ]
// }

Batch Analysis

Analyze multiple texts in a single request:

const results = await analyzer.analyzeBatch([
  "I'm so excited about the new features!",
  "This is really frustrating.",
  "I don't know what to think about this."
]);

console.log(results.count); // 3
results.results.forEach((result, index) => {
  console.log(`Text ${index + 1}: ${result.primaryEmotion} (${result.confidence})`);
});

Configuration Options

const analyzer = new EmotionAnalyzer({
  // Custom base URL for self-hosted instances
  baseUrl: 'https://your-custom-url.com',
  
  // Request timeout in milliseconds (default: 30000)
  timeout: 10000
});

Error Handling

The library provides specific error classes for different failure scenarios:

import { 
  EmotionAnalyzer, 
  ValidationError, 
  RateLimitError, 
  ApiError,
  TimeoutError,
  NetworkError 
} from 'emotion-detector-js';

const analyzer = new EmotionAnalyzer();

try {
  const result = await analyzer.analyze("Your text here");
} catch (error) {
  if (error instanceof ValidationError) {
    // Input validation failed (e.g., text too long)
    console.error('Validation error:', error.message);
    console.error('Field:', error.field);
  } else if (error instanceof RateLimitError) {
    // Rate limit exceeded (429)
    console.error('Rate limit exceeded. Retry after:', error.retryAfter, 'seconds');
  } else if (error instanceof ApiError) {
    // API returned an error
    console.error('API error:', error.message);
    console.error('Status code:', error.statusCode);
  } else if (error instanceof TimeoutError) {
    // Request timed out
    console.error('Request timed out after:', error.timeout, 'ms');
  } else if (error instanceof NetworkError) {
    // Network error occurred
    console.error('Network error:', error.message);
  }
}

API Constraints

| Constraint | Single Analysis | Batch Analysis | |------------|-----------------|----------------| | Max words per text | 100 | 100 | | Max texts | 1 | 10 | | Rate limit | 30 req/min | 10 req/min |

API Reference

EmotionAnalyzer

Constructor

new EmotionAnalyzer(options?: EmotionAnalyzerOptions)

Options:

  • baseUrl?: string - Custom API base URL (default: https://itsKrish01-emotion-checker.hf.space)
  • timeout?: number - Request timeout in milliseconds (default: 30000)

Methods

analyze(text: string): Promise<EmotionResult>

Analyze a single text for emotion.

Parameters:

  • text - The text to analyze (max 100 words)

Returns: EmotionResult

{
  primaryEmotion: string;  // The detected primary emotion
  confidence: number;      // Confidence score (0-1)
  allEmotions: Array<{     // All detected emotions
    emotion: string;
    score: number;
  }>;
}
analyzeBatch(texts: string[]): Promise<BatchEmotionResult>

Analyze multiple texts in a batch.

Parameters:

  • texts - Array of texts to analyze (max 10 texts, 100 words each)

Returns: BatchEmotionResult

{
  results: EmotionResult[];  // Array of results for each input text
  count: number;             // Number of texts analyzed
}

Error Classes

| Error Class | Description | |-------------|-------------| | EmotionAnalyzerError | Base error class | | ValidationError | Input validation failed | | RateLimitError | Rate limit exceeded (HTTP 429) | | ApiError | API returned an error response | | TimeoutError | Request timed out | | NetworkError | Network connection error |

Usage with React

import { useState } from 'react';
import { EmotionAnalyzer, ValidationError, RateLimitError } from 'emotion-detector-js';

const analyzer = new EmotionAnalyzer();

function EmotionDetector() {
  const [text, setText] = useState('');
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  const handleAnalyze = async () => {
    setLoading(true);
    setError(null);
    
    try {
      const result = await analyzer.analyze(text);
      setResult(result);
    } catch (err) {
      if (err instanceof ValidationError) {
        setError(`Validation error: ${err.message}`);
      } else if (err instanceof RateLimitError) {
        setError('Too many requests. Please wait a moment.');
      } else {
        setError('An error occurred. Please try again.');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <textarea 
        value={text} 
        onChange={(e) => setText(e.target.value)}
        placeholder="Enter text to analyze..."
      />
      <button onClick={handleAnalyze} disabled={loading}>
        {loading ? 'Analyzing...' : 'Analyze Emotion'}
      </button>
      
      {error && <p className="error">{error}</p>}
      
      {result && (
        <div>
          <h3>Result:</h3>
          <p>Emotion: {result.primaryEmotion}</p>
          <p>Confidence: {(result.confidence * 100).toFixed(1)}%</p>
        </div>
      )}
    </div>
  );
}

Requirements

  • Node.js 18+ (for native fetch support) or browser environment
  • For older Node.js versions, you'll need a fetch polyfill

Contributing

Contributions are welcome! Here's how you can help:

Getting Started

  1. Fork the repository

    git clone https://github.com/Itskrish01/emotion-detector-js.git
    cd emotion-detector-js
  2. Install dependencies

    npm install
  3. Build the project

    npm run build

Making Changes

  1. Create a new branch for your feature/fix:

    git checkout -b feature/your-feature-name
  2. Make your changes in the src/ directory

  3. Build and test your changes:

    npm run build
  4. Commit your changes with a descriptive message:

    git commit -m "feat: add your feature description"

Commit Message Guidelines

We follow Conventional Commits:

  • feat: - New features
  • fix: - Bug fixes
  • docs: - Documentation changes
  • refactor: - Code refactoring
  • test: - Adding or updating tests
  • chore: - Maintenance tasks

Pull Request Process

  1. Push your branch to your fork:

    git push origin feature/your-feature-name
  2. Open a Pull Request against the main branch

  3. Describe your changes and link any related issues

  4. Wait for review and address any feedback

Development Guidelines

  • Write TypeScript code with proper type annotations
  • Maintain zero dependencies (use native APIs only)
  • Ensure code works in both Node.js and browser environments
  • Add JSDoc comments for public APIs
  • Follow existing code style and patterns

Reporting Issues

Found a bug or have a suggestion? Open an issue with:

  • Clear description of the problem/suggestion
  • Steps to reproduce (for bugs)
  • Expected vs actual behavior
  • Environment details (Node.js version, browser, etc.)

License

MIT