Created
June 16, 2016 09:44
-
-
Save CatTail/6b63a773c07a67304c20260be857b952 to your computer and use it in GitHub Desktop.
transform `Buffer` to text representation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment