ConvertHub JavaScript SDK

Official JavaScript SDK for ConvertHub API v2 - Convert files between 800+ format pairs with a simple, powerful API.
Features
- 800+ Format Conversions - Support for images, documents, audio, video, and more
- Asynchronous Processing - Non-blocking conversion with job-based workflow
- Chunked Uploads - Handle large files (up to 2GB)
- Smart Caching - Automatic caching for repeated conversions
- TypeScript Support - Full type definitions included
- Framework Agnostic - Works with modern JavaScript runtimes (Node.js 18+, Deno, Bun)
- Developer-Friendly - Clean API with detailed error handling
Requirements
- Node.js 18.0 or higher (uses native fetch API and FormData)
- npm or yarn
- ConvertHub API key (Sign up here)
- TypeScript 4.0+ (optional, for TypeScript projects)
Installation
Install via npm:
npm install @converthub/sdk
Or with yarn:
yarn add @converthub/sdk
Quick Start
const { ConvertHubClient } = require('@converthub/sdk');
const client = new ConvertHubClient({
apiKey: 'YOUR_API_KEY'
});
const job = await client.convertFile({
file: 'path/to/document.pdf',
targetFormat: 'docx'
});
const result = await job.waitForCompletion();
if (result.status === 'completed') {
await job.download('output.docx');
console.log('Download URL:', result.result.download_url);
}
TypeScript Quick Start
import { ConvertHubClient, ConversionJob } from '@converthub/sdk';
const client = new ConvertHubClient({
apiKey: process.env.CONVERTHUB_API_KEY as string
});
const job: ConversionJob = await client.convertFile({
file: 'path/to/document.pdf',
targetFormat: 'docx'
});
const result = await job.waitForCompletion();
console.log(result.result?.download_url);
Table of Contents
Authentication
Get your API key from the ConvertHub Dashboard:
const client = new ConvertHubClient({
apiKey: 'YOUR_API_KEY'
});
Configuration Options
const client = new ConvertHubClient({
apiKey: 'YOUR_API_KEY',
baseUrl: 'https://api.converthub.com',
timeout: 600000,
debug: false
});
Account Management
Get Account Information
Retrieve your account details including credits remaining, membership plan, and file size limits:
const accountInfo = await client.getAccount();
console.log('Credits Remaining:', accountInfo.credits_remaining);
console.log('Plan:', accountInfo.plan.name);
console.log('Total Credits:', accountInfo.plan.credits);
console.log('File Size Limit:', accountInfo.plan.file_size_limit_mb, 'MB');
if (accountInfo.credits_remaining < 10) {
console.log('Warning: Running low on credits!');
}
Monitor Usage
const account = await client.getAccount();
const usedCredits = account.plan.credits - account.credits_remaining;
const usagePercent = (usedCredits / account.plan.credits * 100).toFixed(1);
console.log(`Credits Used: ${usedCredits}/${account.plan.credits} (${usagePercent}%)`);
const fileStats = fs.statSync('large-file.pdf');
const fileSizeMB = fileStats.size / 1024 / 1024;
if (fileSizeMB > account.plan.file_size_limit_mb) {
console.log(`File too large for your plan. Max size: ${account.plan.file_size_limit_mb} MB`);
console.log('Please upgrade your plan to convert larger files.');
}
Basic Usage
Convert a File
const job = await client.convertFile({
file: 'path/to/image.png',
targetFormat: 'jpg'
});
console.log('Job ID:', job.jobId);
console.log('Status:', job.status);
Convert from URL
const job = await client.convertFromUrl({
fileUrl: 'https://example.com/document.pdf',
targetFormat: 'docx'
});
while (job.status === 'processing') {
await new Promise(resolve => setTimeout(resolve, 2000));
await job.getStatus();
}
if (job.status === 'completed') {
console.log('Download:', job.result.download_url);
} else {
console.log('Error:', job.message);
}
Check Job Status
const status = await client.getJobStatus('job_123e4567-e89b-12d3-a456-426614174000');
if (status.status === 'completed') {
console.log('Conversion completed!');
console.log('Download URL:', status.result.download_url);
console.log('File size:', status.result.file_size, 'bytes');
console.log('Expires at:', status.result.expires_at);
} else if (status.status === 'failed') {
console.log('Conversion failed:', status.error.message);
} else {
console.log('Still processing...');
}
Download Converted File
const downloadInfo = await client.getDownloadUrl(job.jobId);
console.log('Filename:', downloadInfo.filename);
console.log('Size:', downloadInfo.file_size, 'bytes');
const buffer = await client.downloadFile(job.jobId);
fs.writeFileSync('output.docx', buffer);
await client.downloadFile(job.jobId, 'path/to/save/converted.docx');
console.log('File downloaded successfully!');
Advanced Features
Conversion Options
const job = await client.convertFile({
file: 'path/to/file.jpg',
targetFormat: 'pdf',
outputFilename: 'my-document.pdf',
options: {
quality: 90,
resolution: '1920x1080',
bitrate: '320k',
sample_rate: 44100
}
});
const audioJob = await client.convertFile({
file: 'path/to/audio.wav',
targetFormat: 'mp3',
outputFilename: 'high-quality.mp3',
options: {
bitrate: '320k',
sample_rate: 48000
}
});
Chunked Upload for Large Files
const largeFile = 'path/to/large-video.mov';
const fileSize = fs.statSync(largeFile).size;
const chunkSize = 10 * 1024 * 1024;
const totalChunks = Math.ceil(fileSize / chunkSize);
const session = await client.initChunkedUpload({
filename: 'large-video.mov',
fileSize: fileSize,
totalChunks: totalChunks,
targetFormat: 'mp4',
webhookUrl: 'https://your-app.com/webhook',
metadata: { videoId: '12345' }
});
const job = await session.uploadFile(largeFile, chunkSize);
console.log('Conversion started:', job.jobId);
Manual Chunked Upload
const handle = fs.openSync('large-file.mov', 'r');
const buffer = Buffer.alloc(chunkSize);
const session = await client.initChunkedUpload({
filename: 'large-file.mov',
fileSize: fileSize,
totalChunks: totalChunks,
targetFormat: 'mp4'
});
for (let i = 0; i < totalChunks; i++) {
const bytesRead = fs.readSync(handle, buffer, 0, chunkSize, i * chunkSize);
const chunk = buffer.slice(0, bytesRead);
await session.uploadChunk(i, chunk);
console.log(`Uploaded chunk ${i + 1} of ${totalChunks}`);
}
fs.closeSync(handle);
const job = await session.complete();
Webhooks
const job = await client.convertFile({
file: 'document.pdf',
targetFormat: 'docx',
webhookUrl: 'https://your-app.com/webhooks/conversion-complete'
});
app.post('/webhooks/conversion-complete', (req, res) => {
const payload = req.body;
if (payload.status === 'completed') {
const downloadUrl = payload.result.download_url;
} else {
const error = payload.error.message;
}
res.sendStatus(200);
});
Metadata
const job = await client.convertFile({
file: 'invoice.pdf',
targetFormat: 'png',
metadata: {
user_id: 'user_123',
invoice_id: 'inv_456',
department: 'accounting'
}
});
const status = await client.getJobStatus(job.jobId);
const metadata = status.metadata;
console.log('Invoice ID:', metadata.invoice_id);
Format Discovery
List All Supported Formats
const formats = await client.getSupportedFormats();
console.log('Total formats:', formats.total_formats);
for (const [type, formatList] of Object.entries(formats.formats)) {
console.log(`\n${type}:`);
formatList.forEach(format => {
console.log(` - ${format.extension} (${format.mime_type})`);
});
}
Check Format Support
const conversions = await client.getFormatConversions('png');
console.log('PNG can be converted to:');
conversions.available_conversions.forEach(conv => {
console.log(` - ${conv.target_format}`);
});
const support = await client.checkConversionSupport('pdf', 'docx');
if (support.supported) {
console.log('PDF to DOCX conversion is available');
}
const allConversions = await client.getSupportedConversions();
console.log('All formats:', Object.keys(allConversions.formats));
console.log('PDF converts to:', allConversions.conversion_map['pdf']);
Error Handling
const { ConvertHubError } = require('@converthub/sdk');
try {
const job = await client.convertFile({
file: 'file.pdf',
targetFormat: 'docx'
});
} catch (error) {
if (error instanceof ConvertHubError) {
console.error('API Error:', error.message);
console.error('Error Code:', error.code);
if (error.code === 'VALIDATION_ERROR' && error.details?.validation_errors) {
Object.entries(error.details.validation_errors).forEach(([field, errors]) => {
console.error(` ${field}: ${errors.join(', ')}`);
});
} else if (error.code === 'AUTHENTICATION_REQUIRED') {
console.error('Check your API key');
} else if (error.statusCode === 429) {
const retryAfter = error.details?.retry_after || 60;
console.error(`Rate limited. Retry after ${retryAfter} seconds`);
}
} else {
console.error('Unexpected error:', error.message);
}
}
Examples
Complete Example: Document Processing Pipeline
const { ConvertHubClient, ConvertHubError } = require('@converthub/sdk');
const fs = require('fs');
class DocumentProcessor {
constructor(apiKey) {
this.client = new ConvertHubClient({ apiKey });
}
async processDocument(inputFile, targetFormat) {
try {
console.log(`Starting conversion of ${inputFile} to ${targetFormat}...`);
const job = await this.client.convertFile({
file: inputFile,
targetFormat: targetFormat,
metadata: {
timestamp: Date.now(),
sourceFile: inputFile
}
});
console.log(`Job created: ${job.jobId}`);
const completedJob = await job.waitForCompletion({
pollingInterval: 2000,
maxWaitTime: 120000
});
if (completedJob.status === 'completed') {
const outputFile = `output/${completedJob.result.format}/converted.${targetFormat}`;
await job.download(outputFile);
console.log('✅ Conversion successful!');
console.log('📁 Saved to:', outputFile);
console.log('📏 Size:', completedJob.result.file_size, 'bytes');
await job.deleteFile();
return outputFile;
} else {
console.log('❌ Conversion failed:', completedJob.error?.message);
}
} catch (error) {
if (error instanceof ConvertHubError) {
console.error('❌ API Error:', error.message);
} else {
console.error('❌ Unexpected error:', error.message);
}
}
return null;
}
}
const processor = new DocumentProcessor('YOUR_API_KEY');
processor.processDocument('documents/report.pdf', 'docx');
Batch Processing Example
const files = [
{ input: 'file1.pdf', format: 'docx' },
{ input: 'file2.png', format: 'jpg' },
{ input: 'file3.mp3', format: 'wav' }
];
const jobs = [];
for (const file of files) {
const job = await client.convertFile({
file: file.input,
targetFormat: file.format
});
jobs.push({
job,
input: file.input,
format: file.format
});
console.log(`Started conversion: ${file.input} -> ${file.format}`);
}
for (const jobInfo of jobs) {
const completedJob = await jobInfo.job.waitForCompletion();
if (completedJob.status === 'completed') {
console.log(`✅ ${jobInfo.input} converted successfully`);
} else {
console.log(`❌ ${jobInfo.input} failed:`, completedJob.error?.message);
}
}
TypeScript Example
The SDK includes full TypeScript support with complete type definitions:
import {
ConvertHubClient,
ConversionJob,
ConvertHubError,
ConversionParams,
JobStatus,
ConversionOptions
} from '@converthub/sdk';
class TypedDocumentConverter {
private client: ConvertHubClient;
constructor(apiKey: string) {
this.client = new ConvertHubClient({
apiKey,
timeout: 300000,
debug: process.env.NODE_ENV === 'development'
});
}
async convertWithOptions(
filePath: string,
targetFormat: string,
options?: ConversionOptions
): Promise<JobStatus> {
try {
const params: ConversionParams = {
file: filePath,
targetFormat,
options,
metadata: {
processedAt: new Date().toISOString(),
environment: process.env.NODE_ENV
}
};
const job: ConversionJob = await this.client.convertFile(params);
console.log(`Job started: ${job.jobId}`);
const result: JobStatus = await job.waitForCompletion({
pollingInterval: 3000,
maxWaitTime: 300000
});
if (result.status === 'completed' && result.result) {
console.log(`Download URL: ${result.result.download_url}`);
console.log(`File size: ${result.result.file_size} bytes`);
console.log(`Expires at: ${result.result.expires_at}`);
}
return result;
} catch (error) {
if (error instanceof ConvertHubError) {
console.error(`API Error [${error.code}]: ${error.message}`);
console.error('Status Code:', error.statusCode);
if (error.details) {
console.error('Error Details:', error.details);
}
}
throw error;
}
}
async batchConvert(
files: Array<{ path: string; format: string }>
): Promise<Map<string, JobStatus>> {
const results = new Map<string, JobStatus>();
const promises = files.map(async ({ path, format }) => {
const job = await this.client.convertFile({
file: path,
targetFormat: format
});
const result = await job.waitForCompletion();
results.set(path, result);
return result;
});
await Promise.all(promises);
return results;
}
}
async function main() {
const converter = new TypedDocumentConverter(process.env.CONVERTHUB_API_KEY!);
const result = await converter.convertWithOptions(
'document.pdf',
'docx',
{
quality: 90,
resolution: '1920x1080'
}
);
const batchResults = await converter.batchConvert([
{ path: 'file1.pdf', format: 'docx' },
{ path: 'file2.png', format: 'jpg' }
]);
batchResults.forEach((status, filePath) => {
console.log(`${filePath}: ${status.status}`);
});
}
main().catch(console.error);
API Documentation
For complete API documentation, visit ConvertHub API Docs.
Testing
Run the test suite:
npm test
npm run test:coverage
npm run test:watch
npm run lint:fix
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature)
- Commit your changes (
git commit -m 'Add amazing feature')
- Push to the branch (
git push origin feature/amazing-feature)
- Open a Pull Request
Support
License
This SDK is open-sourced software licensed under the MIT license.
Credits
Developed and maintained by ConvertHub.
Ready to start converting? Get your API key and begin transforming files in minutes!