objecttonbt

Convert an object to Nbt.

Usage no npm install needed!

<script type="module">
  import objecttonbt from 'https://cdn.skypack.dev/objecttonbt';
</script>

README

objecttonbt

Covert an object to a the Named Binary Tag file format.

This is a way to store data in a compressed way instead of useing json.

This implements what is said here!

Usage

First you must import the function to your code.

For Javascript

const { objectToNbt } = require('objecttonbt');

For Typescript

import { objectToNbt } from 'objecttonbt';

To convert an object just run the function with an object as an input.

const test = {};
objectToNbt(test);

It will always return a Buffer instance.

const test = {};
objectToNbt(test); // Should return Buffer <10, 0, 0, 0>

const test2 = {
    value: 10;
};
objectToNbt(test2); // Should return Buffer <10, 0, 0, 3, 5, 0, 118, 97, 108, 117, 101, 10, 0, 0, 0, 0>

Types

You can specify what type tag the value is going to be.

You can do this by making it a string an puting a specific character at the end.

Byte

const byte = {
    b: '10b';
}
objectToNbt(byte);

Short

const short = {
    s: '20s';
}
objectToNbt(short);

Int

const int = {
    i: 30; // Do not put an i at the end just a number value
}
objectToNbt(int);

Long

const long1 = {
    l: '40l';
}
objectToNbt(long1);
const long2 = {
    l: 40n; // You can use BigInts for longs
}
objectToNbt(long2);

Float

const float1 = {
    f: '50.1f';
}
objectToNbt(float1);
const float2 = {
    f: 60.2; // Number values that are floats will be converted to floats
}
objectToNbt(float2);

Double

const double = {
    d: '70.3d',
};
objectToNbt(double);

Arrays

If there are diffent types in an array it will cause an error.

Always make sure ever element in an array is the same type.

Byte Array

const byteArray = {
    ba: [':BA:', 80, 90], // The first index of the array must be ':BA:' or it will do a normal list
};
objectToNbt(byteArray);

Int Array

const intArray = {
    ia: [':IA:', 100, 110], // The first index of the array must be ':IA:' or it will do a normal list
};
objectToNbt(intArray);

Long Array

const longArray = {
    la: [':LA:', 120, 130], // The first index of the array must be ':LA:' or it will do a normal list
};
objectToNbt(longArray);

Other

The data can only be long as the max buffer length.

Functions, Symbols, null, and undefined will default to an empty nameless int. (It also might break the writing prosses)