@litert/bencode
TypeScript icon, indicating that this package has built-in type declarations

0.1.2 • Public • Published

LiteRT/Bencode

npm version License node GitHub issues GitHub Releases

A bencode decode/encode library based on Node.js.

Requirement

  • TypeScript v3.1.x (or newer)
  • Node.js v8.0.0 (or newer)

Installation

npm i @litert/bencode --save

Usage

import * as libBencode from "@litert/bencode";

const be = libBEncode.createBEncoder();

const beData = be.encode({ // Encode data into BEncode.
    "name": "Angus",
    "age": 18,
    "friends": [
        "Edith",
        "Alex"
    ],
    "scores": {
        "math": 87
    },
    "randomBytes": Buffer.allocUnsafe(32)
});

/**
 * Don't print as a UTF-8 string, becuase it's binary.
 */
console.log(beData);

/**
 * Print Buffer in BASE64 format in JSON.
 */
function buffer4Base64(k: string, v: any): any {

    if (typeof v === "object" && "data" in v && v.type === "Buffer") {

        return Buffer.from(v.data).toString("base64");
    }

    return v;
}

/**
 * Print the decoded object as JSON.
 *
 * The second argument of decode will transform a Buffer into string, if it's
 * a UTF-8 string.
 */
console.log(JSON.stringify(
    be.decode(beData, true),
    buffer4Base64,
    2
));

License

This library is published under Apache-2.0 license.

Package Sidebar

Install

npm i @litert/bencode

Weekly Downloads

0

Version

0.1.2

License

Apache-2.0

Unpacked Size

52.7 kB

Total Files

24

Last publish

Collaborators

  • fenying