docstrange
v1.0.7
Published
Official Node.js client for Docstrange API - Extract data from PDFs, images, and documents in multiple formats
Maintainers
Readme
Docstrange Node.js Client
Official Node.js client library for the Docstrange API by Nanonets. Extract data from PDFs, images, and other standard documents in multiple output formats.
🌐 Try it online first! Test document extraction at https://docstrange.nanonets.com to see what's possible before integrating.
Features
- 🚀 Easy Integration - Simple and intuitive API
- 📄 Multiple Formats - Support for PDF, images, and standard documents
- 🎯 Flexible Output - 9 different output formats to choose from
- 💪 TypeScript Support - Full TypeScript definitions included
- ⚡ Async/Await - Modern promise-based API
- 🛡️ Error Handling - Comprehensive error handling and validation
- 🖥️ CLI Support - Extract documents directly from command line
Supported Output Types
flat-json- Flat JSON structure for easy data accessmarkdown- Convert documents to Markdown formatcsv- Extract data as comma-separated valuestext- Plain text extraction (maps to markdown)tables- Structured table data extractionhtml- HTML format with preserved stylinghierarchy- Hierarchical structure preserving document layoutspecified-fields- Extract only specified fieldsspecified-json- Custom JSON structure based on your requirements
Related Projects
- 🐍 Python: docstrange - Official Python client for Docstrange API
Installation
npm install docstrangeQuick Start
💡 New to Docstrange? Try the online interface first to test document extraction before coding!
Step 1: Get Your API Key
Get your free API key from docstrange.nanonets.com:
- Visit docstrange.nanonets.com
- Sign up or log in to your account
- Navigate to the Integrate section
- Copy your API key
Step 2: Set Environment Variable
export DOCSTRANGE_API_KEY="your-api-key-here"Step 3: Use the Client
const DocstrangeClient = require('docstrange');
async function main() {
// Initialize the client (uses DOCSTRANGE_API_KEY automatically)
const client = new DocstrangeClient();
// Extract data directly from document
const result = await client.extractAsJSON('./invoice.pdf');
console.log('Extracted data:', result.content);
console.log('Record ID:', result.recordId);
console.log('Processing time:', result.processingTime);
}
main().catch(console.error);Alternative: Pass API Key Directly
const DocstrangeClient = require('docstrange');
async function main() {
// Initialize with API key directly
const client = new DocstrangeClient('your-api-key');
// Extract data directly from document
const result = await client.extractAsJSON('./invoice.pdf');
console.log('Extracted data:', result.content);
}
main().catch(console.error);CLI Commands
The package includes a CLI tool for direct document processing:
# Set your API key first
export DOCSTRANGE_API_KEY="your-api-key"
# Extract data from documents
docstrange extract <file> [output-type] [output-file]
# Check API key configuration
docstrange status
# Show integration information
docstrange info
# Show help
docstrange helpCLI Document Processing
Extract data directly from the command line using all supported output types:
# Extract as JSON (default)
docstrange extract invoice.pdf
# Convert to Markdown
docstrange extract document.pdf markdown
# Save as CSV file
docstrange extract data.pdf csv output.csv
# Extract as HTML
docstrange extract report.pdf html
# Extract table data
docstrange extract spreadsheet.pdf tables
# Extract hierarchical structure
docstrange extract document.pdf hierarchy
# Extract plain text
docstrange extract file.pdf text
# Extract specific fields (interactive)
docstrange extract invoice.pdf specified-fields
# Extract with JSON schema (interactive)
docstrange extract document.pdf specified-jsonCLI Setup
- Get your free API key from docstrange.nanonets.com → Integrate section
- Set environment variable:
export DOCSTRANGE_API_KEY="your-key" - Use CLI commands:
docstrange extract file.pdf
API Reference
Constructor
// Option 1: Environment variable (recommended)
const client = new DocstrangeClient();
// Uses DOCSTRANGE_API_KEY environment variable
// Option 2: Direct API key
const client = new DocstrangeClient('your-api-key');
// Option 3: Configuration object
const client = new DocstrangeClient({
apiKey: 'your-api-key',
baseUrl: 'https://extraction-api.nanonets.com', // optional
timeout: 30000 // optional, default 30 seconds
});
// Option 4: Explicit environment variable
const client = new DocstrangeClient(process.env.DOCSTRANGE_API_KEY);Document Processing
Extract from File Path
const result = await client.extractFromFile('./document.pdf', {
outputType: 'flat-json', // optional, default 'flat-json'
modelType: 'default', // optional
specifiedFields: ['field1', 'field2'], // for specified-fields output
jsonSchema: { /* your schema */ } // for specified-json output
});
console.log('Content:', result.content);
console.log('Record ID:', result.recordId);
console.log('Processing time:', result.processingTime);Extract from Buffer
const buffer = fs.readFileSync('./document.pdf');
const result = await client.extractFromBuffer(
buffer,
'document.pdf',
{ outputType: 'markdown' }
);Get Result by Record ID
const result = await client.getResult(recordId);
console.log('Content:', result.content);
console.log('Signed URL:', result.signedUrl); // For preview/downloadConvenience Methods
Extract as JSON
const result = await client.extractAsJSON('./document.pdf');Convert to Markdown
const result = await client.convertToMarkdown('./document.pdf');Convert to CSV
const result = await client.convertToCSV('./document.pdf');Convert to HTML
const result = await client.convertToHTML('./document.pdf');Extract Tables
const result = await client.extractTables('./document.pdf');Extract Specified Fields
const result = await client.extractSpecifiedFields('./document.pdf', ['field1', 'field2']);Extract Specified JSON
const schema = { type: 'object', properties: { name: { type: 'string' } } };
const result = await client.extractSpecifiedJSON('./document.pdf', schema);Extract Hierarchy
const result = await client.extractHierarchy('./document.pdf');Extract Plain Text
const result = await client.extractText('./document.pdf');API Key Examples
Environment Variable Setup
// Set environment variable first
// export DOCSTRANGE_API_KEY="your-api-key"
const DocstrangeClient = require('docstrange');
async function checkApiKey() {
// Check if API key is configured
const apiKey = process.env.DOCSTRANGE_API_KEY;
if (!apiKey) {
console.log('Please set DOCSTRANGE_API_KEY environment variable');
console.log('Get your API key from: https://docstrange.nanonets.com → Integrate');
process.exit(1);
}
// Use the client (uses environment variable automatically)
const client = new DocstrangeClient();
return client;
}
checkApiKey().catch(console.error);Error Handling
const DocstrangeClient = require('docstrange');
async function handleErrors() {
try {
const client = new DocstrangeClient();
const result = await client.extractAsJSON('./document.pdf');
console.log('Success:', result);
} catch (error) {
if (error.message.includes('API key is required')) {
console.error('API key required:');
console.error(' Option 1: export DOCSTRANGE_API_KEY="your-key"');
console.error(' Option 2: Pass key to constructor');
console.error(' Get key from: https://docstrange.nanonets.com → Integrate');
} else if (error.statusCode === 401) {
console.error('Invalid API key - please check your key');
} else {
console.error('API Error:', error.message);
}
}
}
handleErrors();Examples
Invoice Processing
import DocstrangeClient from 'docstrange';
async function processInvoice() {
const client = new DocstrangeClient(process.env.DOCSTRANGE_API_KEY!);
// Extract invoice data as JSON
const result = await client.extractAsJSON('./invoice.pdf');
console.log('Invoice data:', result.content);
console.log('Record ID:', result.recordId);
// Or extract specific fields
const fieldsResult = await client.extractSpecifiedFields('./invoice.pdf', [
'invoice_number',
'vendor_name',
'total_amount',
'invoice_date',
'due_date'
]);
console.log('Extracted fields:', fieldsResult.content);
// Or use a JSON schema for structured extraction
const schema = {
type: 'object',
properties: {
invoice_number: { type: 'string' },
vendor_name: { type: 'string' },
total_amount: { type: 'number' },
invoice_date: { type: 'string' },
items: {
type: 'array',
items: {
type: 'object',
properties: {
description: { type: 'string' },
quantity: { type: 'number' },
unit_price: { type: 'number' },
total: { type: 'number' }
}
}
}
}
};
const structuredResult = await client.extractSpecifiedJSON('./invoice.pdf', schema);
console.log('Structured invoice:', structuredResult.content);
}
processInvoice().catch(console.error);Batch Document Processing
import DocstrangeClient from 'docstrange';
import * as fs from 'fs';
import * as path from 'path';
async function batchProcess() {
const client = new DocstrangeClient(process.env.DOCSTRANGE_API_KEY!);
const documentsDir = './documents';
const outputDir = './output';
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
const files = fs.readdirSync(documentsDir);
const supportedExtensions = ['.pdf', '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff'];
for (const file of files) {
const ext = path.extname(file).toLowerCase();
if (supportedExtensions.includes(ext)) {
const filePath = path.join(documentsDir, file);
try {
console.log(`Processing ${file}...`);
// Extract as markdown
const result = await client.convertToMarkdown(filePath);
console.log(`✅ ${file} processed in ${result.processingTime}s`);
console.log(` Pages: ${result.pagesProcessed}, Record ID: ${result.recordId}`);
// Save markdown output
const outputPath = path.join(outputDir, `${file}.md`);
fs.writeFileSync(outputPath, result.content);
console.log(` 💾 Saved to: ${outputPath}`);
} catch (error) {
console.error(`❌ Error processing ${file}:`, error.message);
}
}
}
console.log('🎉 Batch processing completed!');
}
batchProcess().catch(console.error);Multiple Output Formats
import DocstrangeClient from 'docstrange';
async function multipleFormats() {
const client = new DocstrangeClient(process.env.DOCSTRANGE_API_KEY!);
const filePath = './document.pdf';
// Extract in different formats
const formats = [
{ name: 'JSON', method: 'extractAsJSON' },
{ name: 'Markdown', method: 'convertToMarkdown' },
{ name: 'CSV', method: 'convertToCSV' },
{ name: 'HTML', method: 'convertToHTML' },
{ name: 'Tables', method: 'extractTables' },
{ name: 'Hierarchy', method: 'extractHierarchy' },
{ name: 'Text', method: 'extractText' }
];
for (const format of formats) {
try {
console.log(`Extracting as ${format.name}...`);
const result = await client[format.method](filePath);
console.log(`✅ ${format.name}: ${result.content.length} characters`);
console.log(` Processing time: ${result.processingTime}s`);
console.log(` Record ID: ${result.recordId}`);
// Save to file
const ext = format.name.toLowerCase() === 'json' ? 'json' :
format.name.toLowerCase() === 'csv' ? 'csv' :
format.name.toLowerCase() === 'html' ? 'html' : 'md';
require('fs').writeFileSync(`./output/${format.name.toLowerCase()}.${ext}`, result.content);
} catch (error) {
console.error(`❌ ${format.name} failed:`, error.message);
}
}
// Extract specific fields
const fieldsResult = await client.extractSpecifiedFields(filePath, [
'title', 'date', 'amount', 'company'
]);
console.log('Specified fields:', fieldsResult.content);
// Extract with JSON schema
const schema = {
type: 'object',
properties: {
title: { type: 'string' },
amount: { type: 'number' },
items: { type: 'array' }
}
};
const schemaResult = await client.extractSpecifiedJSON(filePath, schema);
console.log('Schema-based extraction:', schemaResult.content);
}
multipleFormats().catch(console.error);Error Handling
The client includes comprehensive error handling:
import DocstrangeClient, { DocstrangeError } from 'docstrange-client';
try {
const client = new DocstrangeClient('your-api-key');
const result = await client.extractAsJSON(workflowId, './document.pdf');
} catch (error) {
if (error.statusCode) {
const docError = error as DocstrangeError;
console.error(`API Error ${docError.statusCode}: ${docError.message}`);
} else {
console.error('Unexpected error:', error);
}
}Environment Variables
You can set your API key as an environment variable:
export DOCSTRANGE_API_KEY="your-api-key"Then use it in your code:
const client = new DocstrangeClient(process.env.DOCSTRANGE_API_KEY!);TypeScript Support
This package includes full TypeScript definitions. All types are exported for your convenience:
import DocstrangeClient, {
OutputType,
ProcessDocumentOptions,
DocumentUploadResponse,
WorkflowResponse,
DocstrangeError
} from 'docstrange-client';Requirements
- Node.js 14.0.0 or higher
- Valid Docstrange API key
Getting Your API Key
- Visit docstrange.nanonets.com
- Sign up or log in to your account
- Navigate to the Integrate section
- Copy your free API key
- Use the API key to initialize the client or set as environment variable
Support
License
MIT License - see LICENSE file for details.
Contributing
We welcome contributions! Please see our Contributing Guide for details.
Made with ❤️ by Nanonets
