# Transformers.js Code Examples Working examples showing how to use Transformers.js across different runtimes and frameworks. All examples use the same task and model for consistency: - **Task**: `feature-extraction` - **Model**: `onnx-community/all-MiniLM-L6-v2-ONNX` ## Table of Contents 1. [Browser (Vanilla JS)](#browser-vanilla-js) 2. [Node.js](#nodejs) 3. [React](#react) 4. [Express API](#express-api) ## Browser (Vanilla JS) ### Basic Usage ```html Feature Extraction

Text Embedding Generator

``` ### With Progress Tracking ```html Feature Extraction with Progress

Text Embedding Generator

Loading model...

``` ## Node.js ### Basic Script ```javascript // embed.js import { pipeline } from '@huggingface/transformers'; async function generateEmbedding(text) { const extractor = await pipeline( 'feature-extraction', 'onnx-community/all-MiniLM-L6-v2-ONNX' ); const output = await extractor(text, { pooling: 'mean', normalize: true }); console.log('Text:', text); console.log('Embedding dimensions:', output.data.length); console.log('First 5 values:', Array.from(output.data).slice(0, 5)); await extractor.dispose(); } generateEmbedding('Hello, world!'); ``` ### Batch Processing ```javascript // batch-embed.js import { pipeline } from '@huggingface/transformers'; import fs from 'fs/promises'; async function embedDocuments(documents) { const extractor = await pipeline( 'feature-extraction', 'onnx-community/all-MiniLM-L6-v2-ONNX' ); console.log(`Processing ${documents.length} documents...`); const embeddings = []; for (let i = 0; i < documents.length; i++) { const output = await extractor(documents[i], { pooling: 'mean', normalize: true }); embeddings.push({ text: documents[i], embedding: Array.from(output.data) }); console.log(`Processed ${i + 1}/${documents.length}`); } await fs.writeFile( 'embeddings.json', JSON.stringify(embeddings, null, 2) ); console.log('Saved to embeddings.json'); await extractor.dispose(); } const documents = [ 'The cat sat on the mat', 'A dog played in the park', 'Machine learning is fascinating' ]; embedDocuments(documents); ``` ### CLI with Progress ```javascript // cli-embed.js import { pipeline } from '@huggingface/transformers'; async function main() { const text = process.argv[2] || 'Hello, world!'; console.log('Loading model...'); const fileProgress = {}; const extractor = await pipeline( 'feature-extraction', 'onnx-community/all-MiniLM-L6-v2-ONNX', { progress_callback: (info) => { if (info.status === 'progress') { fileProgress[info.file] = info.progress; // Show all files progress const progressLines = Object.entries(fileProgress) .map(([file, progress]) => ` ${file}: ${progress.toFixed(1)}%`) .join('\n'); process.stdout.write(`\r\x1b[K${progressLines}`); } if (info.status === 'done') { console.log(`\n✓ ${info.file} complete`); } if (info.status === 'ready') { console.log('\nModel ready!'); } } } ); console.log('Generating embedding...'); const output = await extractor(text, { pooling: 'mean', normalize: true }); console.log(`\nText: "${text}"`); console.log(`Dimensions: ${output.data.length}`); console.log(`First 5 values: ${Array.from(output.data).slice(0, 5).join(', ')}`); await extractor.dispose(); } main(); ``` ## React ### Basic Component ```jsx // EmbeddingGenerator.jsx import { useState, useRef, useEffect } from 'react'; import { pipeline } from '@huggingface/transformers'; export function EmbeddingGenerator() { const extractorRef = useRef(null); const [text, setText] = useState(''); const [embedding, setEmbedding] = useState(null); const [loading, setLoading] = useState(false); const generate = async () => { if (!text) return; setLoading(true); // Load model on first generate if (!extractorRef.current) { extractorRef.current = await pipeline( 'feature-extraction', 'onnx-community/all-MiniLM-L6-v2-ONNX' ); } const output = await extractorRef.current(text, { pooling: 'mean', normalize: true }); setEmbedding(Array.from(output.data)); setLoading(false); }; // Cleanup on unmount useEffect(() => { return () => { if (extractorRef.current) { extractorRef.current.dispose(); } }; }, []); return (

Text Embedding Generator