Node.js SDK Node.js 14+ TypeScript
Build server-side applications with our official Node.js client library
Installation
Install the WebburnsTech Node.js SDK using npm or yarn. Requires Node.js 14 or higher.
npm install @webburnstech/node-sdk
yarn add @webburnstech/node-sdk
pnpm add @webburnstech/node-sdk
The SDK includes full TypeScript definitions. No additional packages required.
Quick Start
Initialize the SDK with your API key and start making requests in seconds.
// CommonJS
const { WebburnsTech } = require('@webburnstech/node-sdk');
// ES Modules / TypeScript
import { WebburnsTech } from '@webburnstech/node-sdk';
// Initialize the client
const client = new WebburnsTech({
apiKey: 'your-api-key-here', // Get from https://dashboard.webburnstech.dev
environment: 'production' // or 'development' for testing
});
// Make your first API call
async function analyzeSentiment() {
try {
const response = await client.nlp.analyzeSentiment({
text: 'WebburnsTech makes AI integration incredibly simple!',
language: 'en'
});
console.log('Sentiment:', response.sentiment); // 'positive'
console.log('Confidence:', response.confidence); // 0.95
console.log('Emotions:', response.emotions); // { joy: 0.8, ... }
} catch (error) {
if (error instanceof WebburnsTech.APIError) {
console.error('API Error:', error.message);
} else {
console.error('Unexpected error:', error);
}
}
}
analyzeSentiment();
API Reference
Explore the complete Node.js SDK API with detailed examples for each method.
Natural Language Processing
Process and understand human language with our advanced NLP models.
Analyze the sentiment and emotional tone of text.
const response = await client.nlp.analyzeSentiment({
text: 'I absolutely love this product! It has changed my workflow completely.',
language: 'en', // optional, auto-detected if not provided
detailed: true // optional, returns emotion breakdown
});
// Response:
{
sentiment: 'positive',
confidence: 0.92,
emotions: {
joy: 0.85,
trust: 0.78,
anticipation: 0.64
}
}
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| text | string | Yes | The text to analyze for sentiment |
| language | string | No | Language code (e.g., 'en', 'es', 'fr'). Auto-detected if not provided. |
| detailed | boolean | No | Whether to return detailed emotion analysis |
Extract named entities (people, organizations, locations) from text.
const response = await client.nlp.extractEntities({
text: 'Apple Inc. was founded by Steve Jobs in Cupertino, California.',
types: ['PERSON', 'ORGANIZATION', 'LOCATION'] // optional filter
});
// Iterate through entities
response.entities.forEach(entity => {
console.log(`Text: ${entity.text}`);
console.log(`Type: ${entity.type}`);
console.log(`Confidence: ${entity.confidence}`);
console.log('---');
});
// Response:
// Text: Apple Inc.
// Type: ORGANIZATION
// Confidence: 0.98
// ---
// Text: Steve Jobs
// Type: PERSON
// Confidence: 0.95
Computer Vision
Analyze and understand visual content with our computer vision models.
Analyze images for objects, scenes, and visual content.
const fs = require('fs');
// From URL
const response = await client.vision.analyzeImage({
image: 'https://example.com/image.jpg',
features: ['objects', 'faces', 'text'] // optional
});
// From local file
const imageBuffer = fs.readFileSync('image.jpg');
const response = await client.vision.analyzeImage({
image: imageBuffer,
features: ['objects', 'colors']
});
// From readable stream
const imageStream = fs.createReadStream('image.jpg');
const response = await client.vision.analyzeImage({
image: imageStream,
features: ['objects', 'faces']
});
// Access results
response.objects.forEach(obj => {
console.log(`Detected: ${obj.label} (confidence: ${obj.confidence})`);
});
if (response.faces) {
response.faces.forEach(face => {
console.log(`Age: ${face.age}, Gender: ${face.gender}`);
console.log(`Emotions: ${face.emotions}`);
});
}
console.log(`Dominant color: ${response.colors.dominant}`);
console.log(`Detected text: ${response.text}`);
Chat & Conversations
Build intelligent conversational interfaces with our chat API.
Start a new conversation with context and personality settings.
// Create a conversation
const conversation = await client.chat.createConversation({
context: 'You are a helpful customer support assistant for a tech company.',
personality: 'friendly', // 'professional', 'casual', 'humorous'
memory: true // remember conversation history
});
// Send messages
const response = await conversation.sendMessage('How do I reset my password?');
console.log('Assistant:', response.message);
console.log('Conversation ID:', response.conversationId);
console.log('Suggestions:', response.suggestions);
// Continue the conversation
const followUp = await conversation.sendMessage('What are my security options?');
console.log('Assistant:', followUp.message);
// Save conversation state for later
const conversationId = conversation.id;
// Later, retrieve the conversation
const conversation = await client.chat.getConversation(conversationId);
Advanced Usage
Learn about advanced features and Node.js-specific configuration options.
Error Handling
Proper error handling for robust Node.js applications.
const { WebburnsTech, APIError, AuthenticationError, RateLimitError } = require('@webburnstech/node-sdk');
try {
const response = await client.nlp.analyzeSentiment({
text: 'Sample text'
});
} catch (error) {
if (error instanceof AuthenticationError) {
console.log('Authentication failed. Please check your API key.');
} else if (error instanceof RateLimitError) {
console.log(`Rate limit exceeded. Retry after: ${error.retryAfter} seconds`);
} else if (error instanceof APIError) {
console.log(`API Error ${error.statusCode}: ${error.message}`);
} else {
console.log('Unexpected error:', error);
}
}
Configuration Options
Customize the SDK behavior with various configuration options.
const { WebburnsTech } = require('@webburnstech/node-sdk');
const https = require('https');
const client = new WebburnsTech({
apiKey: 'your-api-key-here',
// Configuration options
environment: 'production', // 'production' or 'development'
timeout: 30000, // request timeout in milliseconds
maxRetries: 3, // automatic retry attempts
baseURL: 'https://api.webburnstech.dev/v1', // custom API endpoint
// Request logging
debug: false, // enable debug logging
// Custom headers
headers: {
'X-Custom-Header': 'value'
},
// HTTP agent configuration
httpAgent: new https.Agent({
keepAlive: true,
maxSockets: 100,
timeout: 60000
}),
// Proxy configuration
proxy: {
protocol: 'https',
host: 'proxy.example.com',
port: 8080,
auth: {
username: 'user',
password: 'pass'
}
}
});
Streaming Responses
Handle streaming responses for real-time applications.
// Stream chat responses
const stream = await client.chat.createStreamingConversation({
context: 'You are a helpful assistant.',
personality: 'friendly'
});
// Send message and receive stream
const messageStream = await stream.sendMessage('Tell me a story about AI.');
// Handle stream events
messageStream.on('data', (chunk) => {
process.stdout.write(chunk.content);
});
messageStream.on('complete', (fullResponse) => {
console.log('\nStream completed');
console.log('Full response:', fullResponse);
});
messageStream.on('error', (error) => {
console.error('Stream error:', error);
});
// Cancel stream if needed
// messageStream.cancel();
Node.js-Specific Features
Take advantage of Node.js-specific features and best practices.
Environment Variables
Use environment variables for secure configuration management.
// .env file
WEBBURNSTECH_API_KEY=your-api-key-here
WEBBURNSTECH_ENVIRONMENT=production
// In your code
const client = new WebburnsTech({
apiKey: process.env.WEBBURNSTECH_API_KEY,
environment: process.env.WEBBURNSTECH_ENVIRONMENT
});
File System Integration
Seamless integration with Node.js file system operations.
const fs = require('fs').promises;
const path = require('path');
// Process multiple images
const imageDir = './images';
const files = await fs.readdir(imageDir);
for (const file of files) {
if (path.extname(file) === '.jpg') {
const imagePath = path.join(imageDir, file);
const imageBuffer = await fs.readFile(imagePath);
const analysis = await client.vision.analyzeImage({
image: imageBuffer
});
console.log(`Analysis for ${file}:`, analysis);
}
}
Express.js Middleware
Integrate with Express.js for web applications.
const express = require('express');
const { WebburnsTech } = require('@webburnstech/node-sdk');
const app = express();
const client = new WebburnsTech({
apiKey: process.env.WEBBURNSTECH_API_KEY
});
app.post('/analyze-sentiment', async (req, res) => {
try {
const { text } = req.body;
const analysis = await client.nlp.analyzeSentiment({ text });
res.json(analysis);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000);
Performance & Best Practices
Optimize your Node.js applications for performance and reliability.
Connection Pooling
Use connection pooling for high-throughput applications.
const https = require('https');
const { WebburnsTech } = require('@webburnstech/node-sdk');
// Configure HTTP agent for connection pooling
const agent = new https.Agent({
keepAlive: true,
maxSockets: 50, // Maximum number of sockets
maxFreeSockets: 10, // Maximum number of free sockets
timeout: 60000, // Socket timeout
keepAliveMsecs: 1000 // How long to keep sockets alive
});
const client = new WebburnsTech({
apiKey: 'your-api-key-here',
httpAgent: agent,
httpsAgent: agent
});
// Batch processing with connection reuse
async function processBatch(texts) {
const promises = texts.map(text =>
client.nlp.analyzeSentiment({ text })
);
return Promise.all(promises);
}
Error Recovery & Retries
Implement robust error recovery and automatic retry mechanisms.
const { WebburnsTech, RateLimitError } = require('@webburnstech/node-sdk');
async function analyzeWithRetry(text, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await client.nlp.analyzeSentiment({ text });
} catch (error) {
if (error instanceof RateLimitError) {
const waitTime = error.retryAfter * 1000 || Math.pow(2, attempt) * 1000;
console.log(`Rate limited. Waiting ${waitTime}ms before retry ${attempt}`);
await new Promise(resolve => setTimeout(resolve, waitTime));
} else if (attempt === maxRetries) {
throw error; // Final attempt failed
} else {
console.log(`Attempt ${attempt} failed:`, error.message);
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
}
}
// Usage
analyzeWithRetry('Sample text')
.then(analysis => console.log(analysis))
.catch(error => console.error('All retries failed:', error));
Examples & Tutorials
Explore practical Node.js examples and tutorials to get started quickly.
The WebburnsTech Node.js SDK is built for production use with comprehensive error handling, TypeScript support, connection pooling, and follows Node.js best practices for performance and reliability.