# JavaScript NLP libraries

JavaScript NLP libraries analyze text in Node.js and the browser, from splitting it into tokens to tagging words and detecting its language. Local libraries process text with rules, statistics, or pretrained models instead of a hosted API. These libraries let apps and AI agents count model tokens, classify text, and tag parts of speech.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [openai](#openai) | 223.6M | 11.3K | Nov 2026 | Apache-2.0 |
| [AI SDK](#ai) | 172.3M | 28.1K | Nov 2026 | Apache-2.0 |
| [js-tiktoken](#js-tiktoken) | 49.4M | 1.1K | Aug 2025 | MIT |
| [@huggingface/transformers](#huggingface-transformers) | 19.1M | 16.4K | Oct 2026 | Apache-2.0 |
| [gpt-tokenizer](#gpt-tokenizer) | 10.6M | 862 | Nov 2026 | MIT |
| [Natural](#natural) | 7.6M | 10.9K | Oct 2026 | MIT |
| [franc-min](#franc-min) | 7.0M | 4.4K | Jan 2024 | MIT |
| [compromise](#compromise) | 5.7M | 12.2K | Nov 2026 | MIT |

Downloads: npm, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[OpenAI Node](#openai) has the most monthly downloads in this comparison, at 223.6M, a count that covers every use of the OpenAI API rather than text analysis alone.

## Capabilities

| Library | Local processing | Tag words |
| --- | --- | --- |
| [openai](#openai) | No | No |
| [AI SDK](#ai) | No | No |
| [js-tiktoken](#js-tiktoken) | Yes | No |
| [@huggingface/transformers](#huggingface-transformers) | Yes | Yes |
| [gpt-tokenizer](#gpt-tokenizer) | Yes | No |
| [Natural](#natural) | Yes | Yes |
| [franc-min](#franc-min) | Yes | No |
| [compromise](#compromise) | Yes | Yes |

## Libraries

### openai

[GitHub](https://github.com/openai/openai-node) · [npm](https://www.npmjs.com/package/openai) · [Docs](https://github.com/openai/openai-node#readme)

Provides the official TypeScript library for the OpenAI API.

- Downloads / mo: 223.6M
- Stars: 11.3K
- Last release: 7.60.0
- License: Apache-2.0
- Capabilities: [From the openai docs](https://github.com/openai/openai-node#readme)

```sh
npm install openai
```

**langchain-ai/langchainjs** (18.4K stars)

[langchain-ai/langchainjs](https://github.com/langchain-ai/langchainjs) 

```typescript
async _call(values: ChainValues): Promise<ChainValues> {
  const text = values[this.inputKey];
  const moderationRequest: OpenAIClient.ModerationCreateParams = {
    input: text,
  };
  let mod;
  try {
    mod = await this.caller.call(() =>
      this.client.moderations.create(moderationRequest)
    );
  } catch (error) {
    // eslint-disable-next-line no-instanceof/no-instanceof
    if (error instanceof Error) {
      throw error;
    } else {
      throw new Error(error as string);
    }
  }
  const output = this._moderate(text, mod.results[0]);
  return {
    [this.outputKey]: output,
    results: mod.results,
  };
}

```

[langchain/src/chains/openai_moderation.ts](https://github.com/langchain-ai/langchainjs/blob/ff0dc580a71268b098e5ac2ee68b7d98317727ed/langchain/src/chains/openai_moderation.ts#L124-L147) · [More projects using openai →](https://dashboard.exa.ai/playground/search?q=openai%20GitHub%20projects)

**Quickstart**

```typescript
import OpenAI from 'openai'

const client = new OpenAI()
const result = await client.moderations.create({ input: 'Hello, world!' })

```

From [moderations.ts](https://github.com/openai/openai-node/blob/main/src/resources/moderations.ts)

### AI SDK

[GitHub](https://github.com/vercel/ai) · [npm](https://www.npmjs.com/package/ai) · [Docs](https://ai-sdk.dev/docs)

Builds AI apps with a single interface for any model provider.

- Downloads / mo: 172.3M
- Stars: 28.1K
- Last release: 7.0.177
- License: Apache-2.0
- Capabilities: [From the AI SDK docs](https://ai-sdk.dev/docs)

```sh
npm install ai @ai-sdk/cohere
```

**zaidmukaddam/scira** (12.0K stars)

[zaidmukaddam/scira](https://github.com/zaidmukaddam/scira) 

```typescript
async function rerankResults<T>(
  items: T[],
  query: string,
  createDocument: (item: T) => string,
  topN?: number,
): Promise<T[]> {
  if (items.length === 0) return items;

  try {
    const documents = items.map(createDocument);
    const { ranking } = await rerank({
      model: cohere.reranking('rerank-v4.0-pro'),
      query,
      documents,
      topN: topN || items.length,
    });

    return ranking.map((r) => items[r.originalIndex]);
  } catch (error) {
    console.error('Reranking failed, returning original order:', error);
    return items;
  }
}

```

[lib/tools/spotify-search.ts](https://github.com/zaidmukaddam/scira/blob/e1692f5bdec7ec3f6482a24e0c6cf9b483d810f9/lib/tools/spotify-search.ts#L266-L288) · [More projects using AI SDK →](https://dashboard.exa.ai/playground/search?q=ai%20GitHub%20projects)

**Quickstart**

```typescript
import { rerank } from 'ai'
import { cohere } from '@ai-sdk/cohere'

const result = await rerank({ model: cohere.reranking('rerank-v4.0-pro'), query: 'rain', documents: ['a rainy day', 'a sunny day'] })

```

From [reranking](https://ai-sdk.dev/docs/ai-sdk-core/reranking)

### js-tiktoken

[GitHub](https://github.com/dqbd/tiktoken) · [npm](https://www.npmjs.com/package/js-tiktoken) · [Docs](https://github.com/dqbd/tiktoken#readme)

Ports the tiktoken tokenizer to JavaScript.

- Downloads / mo: 49.4M
- Stars: 1.1K
- Last release: 1.0.21
- License: MIT
- Capabilities: [From the js-tiktoken docs](https://github.com/dqbd/tiktoken#readme)

```sh
npm install js-tiktoken
```

**Quickstart**

```typescript
import { getEncoding } from 'js-tiktoken'

const encoder = getEncoding('gpt2')
const tokenIds = encoder.encode('hello world')

```

From [README.md](https://github.com/dqbd/tiktoken/blob/main/js/README.md) · [Find projects using js-tiktoken →](https://dashboard.exa.ai/playground/search?q=js-tiktoken%20GitHub%20projects)

### @huggingface/transformers

[GitHub](https://github.com/huggingface/transformers.js) · [npm](https://www.npmjs.com/package/@huggingface/transformers) · [Docs](https://github.com/huggingface/transformers.js#readme)

Runs Transformers models directly in the browser, with no server.

- Downloads / mo: 19.1M
- Stars: 16.4K
- Last release: 4.3.2
- License: Apache-2.0
- Capabilities: [From the @huggingface/transformers docs](https://github.com/huggingface/transformers.js#readme)

```sh
npm install @huggingface/transformers
```

**huggingface/transformers.js-examples** (2.1K stars)

[huggingface/transformers.js-examples](https://github.com/huggingface/transformers.js-examples) 

```typescript
async (event) => {
  // Retrieve the translation pipeline. When called for the first time,
  // this will load the pipeline and save it for future use.
  const translator = await MyTranslationPipeline.getInstance((x) => {
    // We also add a progress callback to the pipeline so that we can
    // track model loading.
    self.postMessage(x);
  });

  // Capture partial output as it streams from the pipeline
  const streamer = new TextStreamer(translator.tokenizer, {
    skip_prompt: true,
    skip_special_tokens: true,
    callback_function: function (text) {
      self.postMessage({
        status: "update",
        output: text,
      });
    },
  });

  // Actually perform the translation
  const output = await translator(event.data.text, {
    tgt_lang: event.data.tgt_lang,
    src_lang: event.data.src_lang,

    // Allows for partial output
    streamer,
  });

  // Send the output back to the main thread
  self.postMessage({
    status: "complete",
    output,
  });
}

```

[react-translator/src/worker.js](https://github.com/huggingface/transformers.js-examples/blob/204b0948e88cd2bdc046316e78b754359653caea/react-translator/src/worker.js#L23-L58) · [More projects using @huggingface/transformers →](https://dashboard.exa.ai/playground/search?q=%40huggingface/transformers%20GitHub%20projects)

**Quickstart**

```typescript
import { pipeline } from '@huggingface/transformers'

const classifier = await pipeline('sentiment-analysis')
const result = await classifier('I love transformers!')

```

From [README.md](https://github.com/huggingface/transformers.js/blob/main/README.md)

### gpt-tokenizer

[GitHub](https://github.com/niieani/gpt-tokenizer) · [npm](https://www.npmjs.com/package/gpt-tokenizer) · [Docs](https://github.com/niieani/gpt-tokenizer#readme)

Encodes text as BPE tokens for OpenAI models in pure JavaScript.

- Downloads / mo: 10.6M
- Stars: 862
- Last release: 4.1.2
- License: MIT
- Capabilities: [From the gpt-tokenizer docs](https://github.com/niieani/gpt-tokenizer#readme)

```sh
npm install gpt-tokenizer
```

**onlook-dev/onlook** (27.3K stars)

[onlook-dev/onlook](https://github.com/onlook-dev/onlook) 

```typescript
export async function countTokensWithRoles(messages: ChatMessage[]): Promise<number> {
    const perMessageExtra = 4; // ~role + metadata tokens (OpenAI chat format)
    const perReplyExtra = 2; // for assistant reply priming
    let total = 0;
    for (const m of messages) {
        const content = m.parts
            .map((p) => {
                if (p.type === 'text') {
                    return (p as TextUIPart).text;
                } else if (p.type.startsWith('tool-')) {
                    return JSON.stringify((p as ToolUIPart).input); // TODO: check if this is correct
                }
                return '';
            })
            .join('');
        total += encode(content).length + perMessageExtra;
    }
    return total + perReplyExtra;
}

```

[packages/ai/src/tokens/index.ts](https://github.com/onlook-dev/onlook/blob/1f6e0258f461c3ca9a72ccb989c78d1cbff9de29/packages/ai/src/tokens/index.ts#L5-L23) · [More projects using gpt-tokenizer →](https://dashboard.exa.ai/playground/search?q=gpt-tokenizer%20GitHub%20projects)

**continuedev/continue** (36.5K stars)

[continuedev/continue](https://github.com/continuedev/continue) 

```typescript
function countToolCallFunctionTokens(
  toolCallFunction: { name?: string; arguments?: string } | undefined,
): number {
  if (!toolCallFunction) {
    return 0;
  }

  let tokenCount = 0;
  tokenCount += encode(toolCallFunction.name ?? "").length + 10; // Function name and structure overhead
  tokenCount += encode(toolCallFunction.arguments ?? "").length; // Arguments
  return tokenCount;
}

```

[extensions/cli/src/util/tokenizer.ts](https://github.com/continuedev/continue/blob/5522c6f44ca0ac3528b37244818fbfa39b5af470/extensions/cli/src/util/tokenizer.ts#L67) · [More projects using gpt-tokenizer →](https://dashboard.exa.ai/playground/search?q=gpt-tokenizer%20GitHub%20projects)

**Quickstart**

```typescript
import { encode } from 'gpt-tokenizer'

const tokenIds = encode('Hello, world!')

```

From [README.md](https://github.com/niieani/gpt-tokenizer/blob/main/README.md)

### Natural

[GitHub](https://github.com/NaturalNode/natural) · [npm](https://www.npmjs.com/package/natural)

Provides tokenizers, classifiers, word scoring, and other NLP algorithms for Node.js.

- Downloads / mo: 7.6M
- Stars: 10.9K
- Last release: 8.2.6
- License: MIT
- Capabilities: [From the Natural docs](https://github.com/NaturalNode/natural)

**Strengths**

- **Configures token boundaries.** Choose word, Treebank, or regular-expression tokenizers for the input.
- **Trains reusable text classifiers.** Train a BayesClassifier on labeled text, then classify new inputs.

**Watch out for**

- **Sentiment follows word vocabularies.** Scores sum word polarities and account for negation.

```sh
npm install natural
```

**zxcvbn-ts/zxcvbn** (1.2K stars)

[zxcvbn-ts/zxcvbn](https://github.com/zxcvbn-ts/zxcvbn) 

```typescript
const getTokens = async (inputDir: string, counter: TopTokenCounter) => {
  // const tokenizer = tokenizerZh
  // const tokenizer = new natural.TokenizerJa()
  const tokenizer = new natural.AggressiveTokenizerRu()
  let lines = 0
  let filesProcessedCounter = 0
  const files: string[] = fs.globSync(`${inputDir}/**/wiki_*`)
  for (const filePath of files) {
    const readInterface = readline.createInterface({
      input: fs.createReadStream(filePath),
      terminal: false,
    })
    await readLinePromise(readInterface, (line: string) => {
      const tokens = tokenizer.tokenize(line) ?? []
      counter.addTokens(tokens)
      lines += 1
      if (lines % SENTENCES_PER_BATCH === 0) {
        counter.batchPrune()
        console.info(counter.getStats(), `processing: ${filePath}`)
      }
    })
    filesProcessedCounter += 1
    console.info(
      counter.getStats(),
      `processed: ${filePath} ${filesProcessedCounter}/${files.length} `,
    )
  }
}

```

[data-scripts/wikiExtractor/index.ts](https://github.com/zxcvbn-ts/zxcvbn/blob/83efdae34558e792547559a0bf7e4bd7a1477ec7/data-scripts/wikiExtractor/index.ts#L158-L185) · [More projects using Natural →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20natural%20for%20natural%20language%20processing&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```typescript
import natural from 'natural'

const tokenizer = new natural.WordTokenizer()
const words = tokenizer.tokenize('your dog has fleas.')

```

From [sentiment_analysis.html](https://naturalnode.github.io/natural/Tokenizers.html)

### franc-min

[GitHub](https://github.com/wooorm/franc) · [npm](https://www.npmjs.com/package/franc-min) · [Docs](https://github.com/wooorm/franc/tree/main#readme)

Detects the language of a text.

- Downloads / mo: 7.0M
- Stars: 4.4K
- Last release: 6.2.0
- License: MIT
- Capabilities: [From the franc-min docs](https://github.com/wooorm/franc/tree/main#readme)

```sh
npm install franc-min
```

**RSSNext/Folo** (39.3K stars)

[RSSNext/Folo](https://github.com/RSSNext/Folo) 

```typescript
export const checkLanguage = ({
  content,
  language,
}: {
  content: string
  language: SupportedActionLanguage
}) => {
  if (!content) return true
  const pureContent = parseHtml(content)
    .toText()
    .replaceAll(/https?:\/\/\S+|www\.\S+/g, " ")
  const { code } = ACTION_LANGUAGE_MAP[language]
  if (!code) {
    return false
  }

  const sourceLanguage = franc(duplicateIfLengthLessThan(pureContent, 20), {
    only: detectableLanguageCodes,
  })

  return sourceLanguage === code
}

```

[packages/internal/utils/src/language.ts](https://github.com/RSSNext/Folo/blob/292d15d94f9e7680899e1e2567c1c0d48a423f48/packages/internal/utils/src/language.ts#L12-L33) · [More projects using franc-min →](https://dashboard.exa.ai/playground/search?q=franc-min%20GitHub%20projects)

**Quickstart**

```typescript
import { franc } from 'franc-min'

const language = franc('All human beings are born free and equal in dignity and rights.')

```

From [readme.md](https://github.com/wooorm/franc/blob/main/readme.md)

### compromise

[GitHub](https://github.com/spencermountain/compromise) · [npm](https://www.npmjs.com/package/compromise) · [Docs](https://compromise.cool)

Provides rule-based English text tagging, selection, and transformation.

- Downloads / mo: 5.7M
- Stars: 12.2K
- Last release: 14.20.0
- License: MIT
- Capabilities: [From the compromise docs](https://compromise.cool)

**Strengths**

- **Selects and transforms text.** Find matching text spans and change their grammar through chained methods.
- **Supports custom words and tags.** Add domain vocabulary at parse time or through global lexicon methods.

**Watch out for**

- **Transforms mutate the shared document.** Call clone before transforming a copy that must preserve the original.
- **Matches stay within sentence boundaries.** Use the paragraphs plugin when a match must cross sentences.

```sh
npm install compromise
```

**Quickstart**

```typescript
import nlp from 'compromise'

const doc = nlp('she sells seashells by the seashore.')
const past = doc.verbs().toPastTense().text()

```

From [concepts.md](https://github.com/spencermountain/compromise/blob/master/docs/concepts.md) · [Find projects using compromise →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20compromise%20for%20natural%20language%20processing&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

## FAQ

### Which JavaScript NLP library should I use?

[compromise](#compromise) suits rule-based English tagging and text transformation. [Natural](#natural) suits tokenizers, stemmers, and classifiers in Node.js. [Transformers.js](#huggingface-transformers) suits pretrained models for tasks such as translation and token classification.

### What is the OpenAI moderation API?

The OpenAI moderation API classifies text into predefined moderation categories. [OpenAI Node](#openai) calls it as a hosted service rather than running a local model.

### How do I count tokens in JavaScript?

[js-tiktoken](#js-tiktoken) and [gpt-tokenizer](#gpt-tokenizer) encode text into the BPE token IDs that OpenAI models read. Both run locally in pure JavaScript.

### What is Transformers.js?

[Transformers.js](#huggingface-transformers) runs pretrained NLP pipelines and tokenizers locally in the browser or Node.js. The available tasks and languages depend on the model.

### How do I detect the language of text in JavaScript?

[franc-min](#franc-min) identifies the language of a text from statistical evidence across the whole text. It returns a language code rather than tags for each word.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best JavaScript NLP libraries compromise Natural winkNLP NLP.js code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
