Node.js bindings for Apache Thrift RPC system providing client/server libraries, protocols, and transports for cross-language service communication.
—
Production-ready server implementations supporting single and multiplexed services with configurable protocols, transports, event-driven architecture, and comprehensive error handling for Node.js applications.
Standard single-service Thrift server providing efficient request processing with configurable protocols and transports.
/**
* Create a single-service Thrift server
* @param processor - Service processor (usually generated service class)
* @param handler - Service implementation object with method handlers
* @param options - Server configuration options
* @returns Server instance
*/
function createServer(processor, handler, options): Server;
/**
* Basic Thrift server class
*/
class Server extends EventEmitter {
constructor(processor, handler, options);
// Server lifecycle
listen(port, host?, callback?): void;
close(callback?): void;
// Event handling
on(event, listener): void;
emit(event, ...args): void;
// Server properties
connections: Set<Connection>;
listening: boolean;
// Configuration
transport: TransportConstructor;
protocol: ProtocolConstructor;
}Usage Examples:
const thrift = require('thrift');
const MyService = require('./gen-nodejs/MyService');
// Service implementation
const serviceHandler = {
ping: function(callback) {
console.log('Received ping');
callback(null, 'pong');
},
calculate: function(num1, num2, operation, callback) {
let result;
switch (operation) {
case 'ADD':
result = num1 + num2;
break;
case 'SUBTRACT':
result = num1 - num2;
break;
case 'MULTIPLY':
result = num1 * num2;
break;
case 'DIVIDE':
result = num1 / num2;
break;
default:
callback(new Error('Invalid operation'));
return;
}
callback(null, result);
}
};
// Create server with binary protocol and buffered transport
const server = thrift.createServer(MyService, serviceHandler, {
transport: thrift.TBufferedTransport,
protocol: thrift.TBinaryProtocol
});
// Server event handling
server.on('connection', (connection) => {
console.log('Client connected');
});
server.on('disconnect', (connection) => {
console.log('Client disconnected');
});
server.on('error', (error) => {
console.error('Server error:', error);
});
// Start server
server.listen(9090, 'localhost', () => {
console.log('Thrift server listening on port 9090');
});
// Graceful shutdown
process.on('SIGINT', () => {
console.log('Shutting down server...');
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});Advanced server supporting multiple services over a single connection with automatic service routing and processor management.
/**
* Create a multiplexed server supporting multiple services
* @param processor - Multiplexed processor instance
* @param options - Server configuration options
* @returns MultiplexedServer instance
*/
function createMultiplexServer(processor, options): MultiplexedServer;
/**
* Multiplexed Thrift server class
*/
class MultiplexedServer extends EventEmitter {
constructor(processor, options);
// Server lifecycle
listen(port, host?, callback?): void;
close(callback?): void;
// Service management
registerProcessor(serviceName, serviceProcessor, serviceHandler): void;
unregisterProcessor(serviceName): void;
getProcessor(serviceName): Processor;
// Event handling
on(event, listener): void;
emit(event, ...args): void;
// Server properties
connections: Set<Connection>;
listening: boolean;
services: Map<string, Processor>;
// Configuration
transport: TransportConstructor;
protocol: ProtocolConstructor;
}Usage Examples:
const thrift = require('thrift');
const CalculatorService = require('./gen-nodejs/Calculator');
const WeatherService = require('./gen-nodejs/Weather');
// Create multiplexed processor
const processor = new thrift.MultiplexedProcessor();
// Calculator service implementation
const calculatorHandler = {
add: (num1, num2, callback) => {
callback(null, num1 + num2);
},
subtract: (num1, num2, callback) => {
callback(null, num1 - num2);
}
};
// Weather service implementation
const weatherHandler = {
getTemperature: (city, callback) => {
// Simulate weather API call
const temp = Math.round(Math.random() * 40);
callback(null, temp);
},
getForecast: (city, days, callback) => {
const forecast = [];
for (let i = 0; i < days; i++) {
forecast.push({
day: i + 1,
temperature: Math.round(Math.random() * 40),
condition: 'Sunny'
});
}
callback(null, forecast);
}
};
// Register services with multiplexed processor
processor.registerProcessor('Calculator', CalculatorService, calculatorHandler);
processor.registerProcessor('Weather', WeatherService, weatherHandler);
// Create multiplexed server
const server = thrift.createMultiplexServer(processor, {
transport: thrift.TFramedTransport,
protocol: thrift.TBinaryProtocol
});
// Handle service-specific events
server.on('Calculator:request', (method, args) => {
console.log(`Calculator.${method} called with:`, args);
});
server.on('Weather:request', (method, args) => {
console.log(`Weather.${method} called with:`, args);
});
// Start multiplexed server
server.listen(9090, () => {
console.log('Multiplexed server listening on port 9090');
console.log('Available services: Calculator, Weather');
});HTTP and WebSocket server implementation providing web-friendly access to Thrift services with CORS support and flexible routing.
/**
* Create a web server with HTTP and WebSocket support
* @param processor - Service processor or multiplexed processor
* @param options - Web server configuration options
* @returns WebServer instance
*/
function createWebServer(processor, options): WebServer;
/**
* Web Thrift server class with HTTP and WebSocket support
*/
class WebServer extends EventEmitter {
constructor(processor, options);
// Server lifecycle
listen(port, host?, callback?): void;
close(callback?): void;
// HTTP handling
handleRequest(request, response): void;
// WebSocket handling
handleUpgrade(request, socket, head): void;
// Event handling
on(event, listener): void;
emit(event, ...args): void;
// Server properties
httpServer: HttpServer;
wsServer: WebSocketServer;
connections: Set<Connection>;
listening: boolean;
// Configuration
cors: CorsOptions;
static: StaticFileOptions;
protocol: ProtocolConstructor;
}Usage Examples:
const thrift = require('thrift');
const path = require('path');
const ApiService = require('./gen-nodejs/ApiService');
// API service implementation
const apiHandler = {
getData: (id, callback) => {
callback(null, { id, data: `Data for ${id}`, timestamp: Date.now() });
},
saveData: (data, callback) => {
console.log('Saving data:', data);
callback(null, { success: true, id: Date.now() });
}
};
// Create web server with HTTP and WebSocket support
const webServer = thrift.createWebServer(ApiService, apiHandler, {
protocol: thrift.TJSONProtocol,
// CORS configuration
cors: {
origin: ['http://localhost:3000', 'https://myapp.com'],
credentials: true,
methods: ['GET', 'POST', 'OPTIONS']
},
// Static file serving
static: {
root: path.join(__dirname, 'public'),
index: 'index.html'
},
// WebSocket options
websocket: {
path: '/thrift-ws',
maxConnections: 100
}
});
// Handle HTTP requests
webServer.on('request', (req, res) => {
console.log(`HTTP ${req.method} ${req.url}`);
});
// Handle WebSocket connections
webServer.on('websocket:connection', (ws) => {
console.log('WebSocket client connected');
ws.on('close', () => {
console.log('WebSocket client disconnected');
});
});
// Start web server
webServer.listen(8080, () => {
console.log('Web server listening on port 8080');
console.log('HTTP endpoint: http://localhost:8080/');
console.log('WebSocket endpoint: ws://localhost:8080/thrift-ws');
});// Common server configuration interface
interface ServerOptions {
/** Transport class to use for connections */
transport?: TransportConstructor;
/** Protocol class to use for serialization */
protocol?: ProtocolConstructor;
/** Enable TLS/SSL encryption */
tls?: TLSOptions;
/** Connection timeout in milliseconds */
timeout?: number;
/** Maximum number of concurrent connections */
maxConnections?: number;
/** Enable keep-alive for connections */
keepAlive?: boolean;
/** Custom error handler function */
errorHandler?: (error: Error, connection: Connection) => void;
}
// TLS/SSL configuration
interface TLSOptions {
/** Private key file path or buffer */
key?: string | Buffer;
/** Certificate file path or buffer */
cert?: string | Buffer;
/** Certificate Authority certificates */
ca?: string | Buffer | Array<string | Buffer>;
/** Require client certificates */
requestCert?: boolean;
/** Reject unauthorized certificates */
rejectUnauthorized?: boolean;
}
// Web server specific options
interface WebServerOptions extends ServerOptions {
/** CORS configuration */
cors?: CorsOptions;
/** Static file serving options */
static?: StaticFileOptions;
/** WebSocket configuration */
websocket?: WebSocketOptions;
}
// CORS configuration
interface CorsOptions {
/** Allowed origins */
origin?: string | string[] | RegExp;
/** Allowed methods */
methods?: string[];
/** Allowed headers */
allowedHeaders?: string[];
/** Enable credentials */
credentials?: boolean;
}// Server event types and handlers
interface ServerEvents {
/** Emitted when server starts listening */
'listening': () => void;
/** Emitted when a client connects */
'connection': (connection: Connection) => void;
/** Emitted when a client disconnects */
'disconnect': (connection: Connection) => void;
/** Emitted on server errors */
'error': (error: Error) => void;
/** Emitted before processing a request */
'request': (method: string, args: any[]) => void;
/** Emitted after processing a request */
'response': (method: string, result: any) => void;
/** Emitted when server is closing */
'close': () => void;
}
// Multiplexed server additional events
interface MultiplexedServerEvents extends ServerEvents {
/** Emitted for service-specific requests */
[serviceName: string]: (method: string, args: any[]) => void;
}
// Web server additional events
interface WebServerEvents extends ServerEvents {
/** Emitted for HTTP requests */
'request': (req: IncomingMessage, res: ServerResponse) => void;
/** Emitted for WebSocket connections */
'websocket:connection': (ws: WebSocket) => void;
/** Emitted for WebSocket disconnections */
'websocket:disconnect': (ws: WebSocket) => void;
}// Server error handling patterns
interface ErrorHandling {
// Global error handler
server.on('error', (error) => {
console.error('Server error:', error);
// Log error, send alerts, etc.
});
// Connection-specific error handler
server.on('connection', (connection) => {
connection.on('error', (error) => {
console.error('Connection error:', error);
// Handle connection-specific errors
});
});
// Service method error handling
serviceHandler: {
myMethod: (args, callback) => {
try {
const result = processRequest(args);
callback(null, result);
} catch (error) {
callback(error); // Pass error to Thrift framework
}
}
};
}Install with Tessl CLI
npx tessl i tessl/npm-thrift