CatTail
6/16/2016 - 9:44 AM

transform `Buffer` to text representation

transform Buffer to text representation

'use strict'

const dgram = require('dgram')
const Packet = require('native-dns-packet')

const server = dgram.createSocket('udp4', (msg, rinfo) => {
    console.log(rinfo)
    console.log(msg, Buffer.byteLength(msg))
    console.log(bufferToString(msg, 16, 1, 2))
    console.log(Packet.parse(msg))
})

server.bind(53)

// buffer <= <Buffer df de 01 00 00 01 00 00 00 00 00 00 07 63 61 74 74 61 69 6c 02 6d 65 00 00 01 00 01>
// bufferToString(msg, 16, 1, 2) =>
//
//   df de
//   01 00
//   00 01
//   00 00
//   00 00
//   00 00
//   07 63
//   61 74
//   74 61
//   69 6c
//   02 6d
//   65 00
//   00 01
//   00 01
function bufferToString(buffer, radix, size, width) {
    let length = Buffer.byteLength(buffer)
    return range(length)
        .map((index) => byteToString(buffer[index], radix))
        .reduce(reduceTextArray(size, ''), [])
        .reduce(reduceTextArray(width, ' '), [])
        .join('\n')
}

// range(3) => [0, 1, 2]
function range(length) {
    return Array.apply(null, new Array(length)).map((_, index) => index)
}

// Convert byte to radix represent of text, left padding with "0"
// byte = new Buffer([0x2f])[0]
// byteToString(byte, 2) => '0010111'
function byteToString(byte, radix) {
    let binary = byte.toString(radix)
    let padding = (8 / Math.log2(radix)) - binary.length
    return (new Array(padding + 1)).join('0') + binary
}

// Group continuous texts with seperator
// input = ['a', 'b', 'c', 'd']
// input.reduce(reduceTextArray(2, ' '), []) => ['a b', 'c d']
function reduceTextArray(size, seperator) {
    return (arr, text, index) => {
        if (index % size) {
            arr[arr.length - 1] = arr[arr.length - 1] + seperator + text
        } else {
            arr.push(text)
        }
        return arr
    }
}