keichi / binary-parser

A blazing-fast declarative parser builder for binary data
MIT License
857 stars 133 forks source link

How to use it in js #253

Closed MBurtsev closed 6 months ago

MBurtsev commented 6 months ago

Hi I found the library on ts. Can this be used in pure js? I tried using two different online ts -> js converters. After this nothing works.

MBurtsev commented 6 months ago

after npm I got js, but it still no work

MBurtsev commented 6 months ago

image

keichi commented 6 months ago

You can use the ES6 module we publish as a part of the NPM package. Alternatively you can use tools like browserify to convert and bundle the CJS module yourself.

<script type="module">
import { Parser } from "https://unpkg.com/binary-parser@2.2.1/dist/esm/binary_parser.mjs";

// Build an IP packet header Parser
const ipHeader = new Parser()
  .endianness("big")
  .bit4("version")
  .bit4("headerLength")
  .uint8("tos")
  .uint16("packetLength")
  .uint16("id")
  .bit3("offset")
  .bit13("fragOffset")
  .uint8("ttl")
  .uint8("protocol")
  .uint16("checksum")
  .array("src", {
    type: "uint8",
    length: 4
  })
  .array("dst", {
    type: "uint8",
    length: 4
  });

// Prepare buffer to parse.
const buf = new Uint8Array([0x45, 0x00, 0x02, 0xc5, 0x93, 0x99, 0x00, 0x00, 0x2c, 0x06, 0xef, 0x98,
                            0xad, 0xc2, 0x4f, 0x6c, 0x85, 0x01, 0x86, 0xd1]);

// Parse buffer and show result
console.log(ipHeader.parse(buf));
</script>