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

extraer-datos-ine

v1.0.0

Published

SDK oficial de Extraer Datos de INE — API de OCR para credenciales INE/IFE mexicanas (CURP, clave de elector, dirección y más).

Readme

extraer-datos-ine

SDK oficial en JavaScript / TypeScript para la API de OCR para INE de Extraer Datos de INE — extrae CURP, nombre, clave de elector, dirección y todos los campos de una credencial para votar mexicana (INE/IFE) a partir de una imagen, en segundos.

  • 🇲🇽 Diseñado para credenciales INE e IFE (todos los modelos).
  • 🧩 Cero dependencias. Usa el fetch/FormData nativos de Node 18+ (y navegadores).
  • 🔠 TypeScript de primera clase: tipos para los 20 campos y para cada código de error.
  • 📦 Doble build ESM + CommonJS.

📚 Documentación de la API: https://extraerdatosdeine.com/docs 🔑 Consigue una API key con 20 extracciones gratis: https://extraerdatosdeine.com/register


Instalación

npm install extraer-datos-ine

Requiere Node.js 18 o superior (por fetch, FormData y Blob globales).

Uso rápido

import { readFile } from 'node:fs/promises'
import { IneExtractorClient } from 'extraer-datos-ine'

const client = new IneExtractorClient({ apiKey: process.env.INE_API_KEY! })

const front = await readFile('./ine_frente.jpg')
const back = await readFile('./ine_reverso.jpg') // opcional, para CIC/OCR del reverso

const { data, tokensRemaining } = await client.extract({ front, back })

console.log(data.curp)          // 'PEGJ850101HDFRRL09'
console.log(data.claveElector)  // 'PRGRJN85010109H100'
console.log(tokensRemaining)    // 19

Consultar saldo de tokens

const balance = await client.getBalance()
console.log(`Tokens disponibles: ${balance}`)

Formas de enviar la imagen

El SDK elige el método de envío automáticamente según el tipo de front/back.

| Tipo de entrada | Ejemplo | Método HTTP usado | |---|---|---| | Binario | Buffer / Uint8Array / Blob | multipart/form-data | | Base64 | { base64: '...' } o 'data:image/jpeg;base64,...' | JSON base64 | | URL | { url: 'https://...' } | JSON URL (la API descarga la imagen) |

// Binario (recomendado en backend)
await client.extract({ front: buffer, frontMimeType: 'image/png' })

// Base64
await client.extract({ front: { base64 }, back: { base64: back64 } })

// URL HTTPS
await client.extract({ front: { url }, back: { url: backUrl } })

front y back deben ser del mismo tipo: la API no mezcla métodos en una sola petición.

Manejo de errores

Toda respuesta no exitosa lanza un IneExtractorError con un code legible por máquina.

import { IneExtractorError } from 'extraer-datos-ine'

try {
  const { data } = await client.extract({ front })
} catch (err) {
  if (err instanceof IneExtractorError) {
    switch (err.code) {
      case 'INSUFFICIENT_TOKENS':
        console.error('Sin tokens. Recarga en:', err.enrollUrl)
        break
      case 'LOW_IMAGE_QUALITY':
        console.error('Imagen ilegible. Campos faltantes:', err.missingFields)
        break
      case 'IMAGE_TOO_LARGE':
        console.error('La imagen excede 10 MB.')
        break
      default:
        console.error(`[${err.code}] ${err.message}`)
    }
  } else {
    throw err
  }
}

Códigos de error

| code | HTTP | Significado | |---|---|---| | MISSING_API_KEY | 401 | No se envió la API key | | INVALID_API_KEY | 401 | API key inválida o revocada | | MISSING_IMAGE | 400 | Falta la imagen frontal | | INVALID_IMAGE_FORMAT | 400 | Formato no soportado (usa JPEG, PNG o WebP) | | IMAGE_TOO_LARGE | 400 | La imagen excede 10 MB | | INVALID_BASE64 | 400 | Error al decodificar base64 | | INVALID_MULTIPART | 400 | Error al procesar el formulario multipart | | URL_FETCH_FAILED | 400 | No se pudo descargar la imagen de la URL | | URL_INVALID | 400 | URL inválida (debe ser HTTPS) | | URL_BLOCKED | 400 | URL bloqueada por seguridad | | URL_TIMEOUT | 400 | Timeout al descargar la imagen (10 s) | | UNSUPPORTED_CONTENT_TYPE | 415 | Content-Type no soportado | | INSUFFICIENT_TOKENS | 402 | Saldo insuficiente (ver err.enrollUrl) | | LOW_IMAGE_QUALITY | 422 | Imagen ilegible (ver err.missingFields) | | EXTRACTION_FAILED | 500 | Falló la extracción (el token se reembolsa) | | PROCESSING_ERROR | 500 | Error procesando la imagen (token reembolsado) | | INTERNAL_ERROR | 500 | Error interno del servidor | | NETWORK_ERROR | — | Fallo de red (lado del cliente) | | TIMEOUT | — | Se superó el timeoutMs del cliente |

Campos extraídos (IneData)

nombre, apellidoPaterno, apellidoMaterno, domicilio, calle, colonia, codigoPostal, municipio, estado, seccion, curp, claveElector, anioRegistro, fechaNacimiento, sexo, vigencia, numeroVertical, ocr, cic, emision.

Los cuatro últimos (numeroVertical, ocr, cic, emision) viven en el reverso: envía también back para obtenerlos. ¿Dudas sobre CIC vs OCR vs clave de elector? Lee la guía.

Configuración del cliente

new IneExtractorClient({
  apiKey: 'ine_...',              // requerido
  baseUrl: 'https://extraerdatosdeine.com/api/v1', // default
  timeoutMs: 60_000,             // default
  fetch: customFetch,            // opcional (tests / polyfills)
})

Desarrollo

npm install
npm run build      # compila ESM + CJS + .d.ts con tsup
npm test           # build + node --test
npm run typecheck

Enlaces

  • 🌐 Sitio: https://extraerdatosdeine.com
  • 📚 Documentación de la API: https://extraerdatosdeine.com/docs
  • 🔑 Crear cuenta (20 extracciones gratis): https://extraerdatosdeine.com/register
  • 📝 Blog: https://extraerdatosdeine.com/blog

Licencia

MIT © Extraer Datos de INE