Skip to content

Instantly share code, notes, and snippets.

@hillar
Created January 26, 2022 10:07
Show Gist options
  • Save hillar/c2772147033355327a6abe64811da22d to your computer and use it in GitHub Desktop.
Save hillar/c2772147033355327a6abe64811da22d to your computer and use it in GitHub Desktop.
influxdb v1.8 udp only client write points
import dgram from 'dgram';
export class InfluxUdp {
constructor(opts = {}) {
this.host = opts.hostname || opts.host || '127.0.0.1';
this.port = opts.port || 8089;
this.family = opts.family || 'udp4'
if (!(this.family === 'udp4' || this.family === 'udp6')) throw new Error('The family of socket must be either udp4 or udp6')
this.client = dgram.createSocket(this.family)
try {
this.client.connect(this.port, this.host)
this.ok = true
} catch (error) {
throw error
}
}
close(){
setTimeout(() => {
try {
this.client.close()
} catch (error) {
//noop
}
},1000)
}
send(points) {
for (const message of this._encode(points)) {
process.nextTick(() => {
try {
this.client.send(message)
} catch (error) {
//noop
}
})
}
}
_encode(o){
let msg = ''
const msgs = []
const measurement = Object.keys(o)[0]
let tags = []
let values = []
for (const key of Object.keys(o[measurement])){
if (typeof o[measurement][key] === 'string'){
tags.push(key+'='+o[measurement][key])
} else {
if (o[measurement][key] !== undefined) values.push(key+'='+o[measurement][key])
}
}
msg += measurement
if (tags.length) msg += ','+tags.join(',')
msg += ' '+values.join(',')
return [Buffer.from(msg)]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment