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
Maintainers
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:
- Python 3 (3.7 or higher)
- pyscard library
- PC/SC Smart Card Service (usually pre-installed on macOS/Linux, or install PCSC Lite)
- 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 pyscardVerify 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-readerThat's it! The package will automatically:
- ✅ Download executable from releases (recommended - no Python needed!)
- ✅ Build executable locally (if PyInstaller available)
- ✅ 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:winThe 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 respondingTimeout: บัตรไม่ตอบสนอง- 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 --forceOr build a standalone executable to avoid Python dependencies:
npm run build:executablepyscard not found
# Install pyscard
pip3 install pyscard
# Verify installation
python3 -c "from smartcard.System import readers; print('OK')"No readers found
- Ensure card reader is connected
- Check if PC/SC service is running:
# macOS/Linux pcsc_scan - 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 inLicense
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
