UNPKG

tami

Version:

Typescript client for asterisk's AMI

53 lines (52 loc) 1.54 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Connection = void 0; const net = require("net"); const events_1 = require("events"); class Connection extends events_1.EventEmitter { constructor(host, port) { super(); this.host = host; this.port = port || 5038; this.buffer = []; } connect() { this.socket = net.createConnection(this.port, this.host, () => { this.emit('connected', this); }); this.socket.on('close', this.handleClose.bind(this)); this.socket.on('data', this.handleData.bind(this)); this.socket.on('error', this.handleError.bind(this)); return this; } disconnect() { this.socket.removeAllListeners(); this.socket.destroy(); } write(action) { return this.socket.write(action); } handleClose() { this.emit('disconnect'); } handleData(buffer) { const chunk = buffer.toString().split('\r\n\r\n'); if (chunk.length === 1) { this.buffer.push(chunk[0]); } else if (chunk.length === 2) { this.emit('data', this.buffer.concat(chunk[0]).join('')); this.buffer = []; } else { chunk.forEach((value) => { this.emit('data', this.buffer.concat(value).join('')); this.buffer = []; }); } } handleError(err) { this.emit('error', err); } } exports.Connection = Connection;