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

thai-id-reader-pyscard

v1.0.0

Published

Thai ID Card Reader library for Node.js - Read Thai national ID card data using PC/SC protocol

Readme

@erp/thai-id-reader

Thai ID Card Reader library for Node.js - Read Thai national ID card data using PC/SC protocol.

🚀 Zero Setup - Install and use immediately!

npm install @erp/thai-id-reader
# That's it! No Python setup required (if executable is available).

Features

  • 📇 Read Thai national ID card data (Citizen ID, Name, Birth Date, Gender, Address, etc.)
  • 🖼️ Extract photo from ID card (base64 encoded)
  • 🔌 Support multiple card readers
  • 🎯 TypeScript support with full type definitions
  • 🔧 Flexible configuration options
  • 🚀 Works with npm, yarn, bun, and pnpm
  • 📦 Standalone executable support - No Python required! (see BUILD_EXECUTABLE.md)

Prerequisites

Option 1: Standalone Executable (Recommended - No Python Required!)

If you build a standalone executable, no Python installation is needed on the target machine!

See BUILD_EXECUTABLE.md for instructions.

Option 2: Python Script (Fallback)

If using Python script (default), you need:

  1. Python 3 (3.7 or higher)
  2. pyscard library
  3. PC/SC Smart Card Service (usually pre-installed on macOS/Linux, or install PCSC Lite)
  4. Card Reader compatible with PC/SC protocol

Installation

Install Python dependencies (only if using Python script)

# macOS
pip3 install pyscard

# macOS (if permission error)
pip3 install --user pyscard

# Linux (Ubuntu/Debian)
sudo apt-get install pcscd pcsc-tools
pip3 install pyscard

# Windows
# Install PC/SC drivers for your card reader
pip install pyscard

Verify installation

Quick check:

# Using the provided script
npm run check-deps

# Or manually
python3 -c "from smartcard.System import readers; print('OK')"
python3 -c "from smartcard.System import readers; print(readers())"

Note:

  • The Python script (scripts/read-card.py) is ready to use - no code changes needed!
  • For production: Consider building a standalone executable to avoid Python dependencies (see BUILD_EXECUTABLE.md)
  • The library automatically uses executable if available, falls back to Python script otherwise

Installation

# Using npm
npm install @erp/thai-id-reader

# Using yarn
yarn add @erp/thai-id-reader

# Using bun
bun add @erp/thai-id-reader

# Using pnpm
pnpm add @erp/thai-id-reader

That's it! The package will automatically:

  1. ✅ Download executable from releases (recommended - no Python needed!)
  2. ✅ Build executable locally (if PyInstaller available)
  3. ✅ Fallback to Python script (requires Python + pyscard)

Package size: ~20KB (executable downloaded separately, ~15-30MB per platform)

See QUICK_START.md for more details.

Usage

Basic Usage

import { ThaiIDCardReader } from '@erp/thai-id-reader';

const reader = new ThaiIDCardReader();

try {
  const cardData = await reader.readCard();
  console.log('Citizen ID:', cardData.citizenId);
  console.log('Name (TH):', cardData.nameTh);
  console.log('Name (EN):', cardData.nameEn);
  console.log('Birth Date:', cardData.birthDate);
  console.log('Gender:', cardData.gender);
  console.log('Address:', cardData.address);
} catch (error) {
  console.error('Error reading card:', error.message);
}

List Available Readers

import { ThaiIDCardReader } from '@erp/thai-id-reader';

const readers = await ThaiIDCardReader.listReaders();
console.log('Available readers:', readers);

// Use specific reader
const reader = new ThaiIDCardReader();
const cardData = await reader.readCard(readers[0]);

Advanced Configuration

import { ThaiIDCardReader } from '@erp/thai-id-reader';

const reader = new ThaiIDCardReader({
  pythonCommand: 'python3', // or 'python' (only used if Python script is used)
  pythonScriptPath: '/custom/path/to/read-card.py', // or executable path
  timeout: 30000, // 30 seconds
});

const cardData = await reader.readCard();

Using with NestJS

// card-reader.service.ts
import { Injectable } from '@nestjs/common';
import { ThaiIDCardReader } from '@erp/thai-id-reader';

@Injectable()
export class CardReaderService {
  private reader: ThaiIDCardReader;

  constructor() {
    this.reader = new ThaiIDCardReader();
  }

  async readCard() {
    return await this.reader.readCard();
  }

  async listReaders() {
    return await ThaiIDCardReader.listReaders();
  }
}
// card-reader.controller.ts
import { Controller, Get } from '@nestjs/common';
import { CardReaderService } from './card-reader.service';

@Controller('card-reader')
export class CardReaderController {
  constructor(private readonly cardReaderService: CardReaderService) {}

  @Get('read')
  async readCard() {
    try {
      const data = await this.cardReaderService.readCard();
      return { success: true, data };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  @Get('readers')
  async listReaders() {
    const readers = await this.cardReaderService.listReaders();
    return { readers };
  }
}

Building Standalone Executable (No Python Required!)

To avoid Python dependencies on target machines, build a standalone executable:

# macOS/Linux
npm run build:executable

# Windows
npm run build:executable:win

The executable will be created at scripts/dist/read-card (or read-card.exe on Windows).

The library automatically detects and uses the executable if available!

See BUILD_EXECUTABLE.md for detailed instructions.

API Reference

ThaiIDCardReader

Constructor

new ThaiIDCardReader(options?: ThaiIDCardReaderOptions)

Options:

  • pythonScriptPath?: string - Custom path to Python script or executable (default: bundled script/executable)
  • pythonCommand?: string - Python command to use (default: 'python3', only used if Python script is used)
  • timeout?: number - Timeout in milliseconds (default: 30000)

Methods

readCard(readerName?: string): Promise<ThaiIDCardData>

Read card data from the ID card.

Parameters:

  • readerName?: string - Optional reader name. If not provided, uses the first available reader.

Returns: Promise resolving to ThaiIDCardData

Throws: Error if card cannot be read or if Python script/executable is not found

listReaders(): Promise<string[]>

List available card readers (static method).

Returns: Promise resolving to array of reader names

Types

ThaiIDCardData

interface ThaiIDCardData {
  citizenId: string;        // 13-digit citizen ID
  nameTh: string;          // Thai name
  nameEn: string;          // English name
  birthDate: string;       // Format: YYYY-MM-DD
  gender: 'ชาย' | 'หญิง';   // Gender in Thai
  address: string;         // Full address
  issueDate: string;       // Format: YYYY-MM-DD
  expireDate: string;      // Format: YYYY-MM-DD or 'ตลอดชีพ' (lifetime)
  photo?: string;          // Base64 encoded image (optional)
}

Error Handling

The library provides Thai error messages for common errors:

  • ไม่พบบัตร - No card present
  • บัตรไม่ได้รับไฟ - Card not powered
  • บัตรไม่ตอบสนอง - Card not responding
  • Timeout: บัตรไม่ตอบสนอง - Timeout error

Always wrap calls in try-catch blocks:

try {
  const cardData = await reader.readCard();
  // Process card data
} catch (error) {
  if (error.message.includes('ไม่พบบัตร')) {
    // Handle no card scenario
  } else {
    // Handle other errors
  }
}

Troubleshooting

Python script not found

If you get an error about Python script not found, ensure the package is properly installed:

# Reinstall the package
npm install @erp/thai-id-reader --force

Or build a standalone executable to avoid Python dependencies:

npm run build:executable

pyscard not found

# Install pyscard
pip3 install pyscard

# Verify installation
python3 -c "from smartcard.System import readers; print('OK')"

No readers found

  1. Ensure card reader is connected
  2. Check if PC/SC service is running:
    # macOS/Linux
    pcsc_scan
  3. Verify readers are detected:
    python3 -c "from smartcard.System import readers; print(readers())"

Permission errors (Linux)

On Linux, you may need to add your user to the pcscd group:

sudo usermod -a -G pcscd $USER
# Log out and log back in

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.