A drop-in replacement for smart-buffer that does not rely on the Buffer global.
npm install smart-arraybuffersmart-arraybuffer
=============
smart-arraybuffer is a fork of smart-buffer that does not rely on the presence of a Buffer global, but uses an ArrayBuffer combined with DataView instead.
It therefore works in the browser without needing a polyfill like buffer for the browser.
I was inspired to create this module by this post from Sindre Sorhus as I saw that something like that was not available yet.
Key Features:
- Has the exact same api and features as smart-buffer so it can be used as a drop-in replacement in most cases (see below).
- Browser support without the need for a polyfill
- ESM-only. Use --experimental-require-module, or dynamic import() if you're still on cjs.
Requirements:
- Node v18+. It may work on lower versions, but no support for non-LTS versions is guaranteed.
npm install smart-arraybuffer
Note: The published NPM package includes the built javascript library.
If you cloned this repo and wish to build the library manually use:
npm run build
While smart-arraybuffer has almost the exact same api as the original smart-buffer package, there are a few things you need to be aware of if you want to use it as a drop-in replacement:
- The property .internalBuffer is not available. It has been replaced by .internalArrayBuffer and .internalUint8Array, which returns the underlying ArrayBuffer or Uint8Arrayinstance instead of the underlying Buffer instance. If you were relying on .internalBuffer, you cannot use it as a drop-in replacement.
- The .writeString() functions don't support all encodings that Buffer does, only utf8, utf-8, ascii, base64, hex and binary are supported. This is because the module relies on TextEncoder to perform the encoding, which only supports utf8. Given that base64, hex and binary are so common, they have been implemented manually. If you need support for other encodings, like utf-16le, then you still need to work with Node's native Buffer, which kind of defeats the purpose of this module. On the upside, the .readString() methods support all encodings that TextDecoder supports, which is a lot more than what Node's Buffer does.
- Adds a bunch of new methods like .toArrayBuffer(), .toUint8Array(), .readUint8Array(), .writeUint8Array() that are meant to replace their buffer equivalents.
- If you're working in Node.js - meaning the Buffer global is available - then you can still use the buffer methods (.toBuffer(), .readBuffer(), writeBuffer() etc.). However, doing so kind of defeats the purpose of the module, but it may help for incrementally migrating away from Node.js buffer: just keep using .toBuffer() where the calling code actually needs a Node.js buffer, and use .toUint8Array() or .toArrayBuffer() where already possible.
``javascript
// Javascript
import { SmartBuffer } from 'smart-arraybuffer';
// Typescript
import { SmartBuffer, SmartBufferOptions} from 'smart-arraybuffer';
// Or if you want to emphasize that you're using smart-arraybuffer instead of smart-buffer
import { SmartArrayBuffer } from 'smart-arraybuffer';
console.log(SmartArrayBuffer === SmartBuffer); // true
`
Building a packet that uses the following protocol specification:
[PacketType:2][PacketLength:2][Data:XX]
To build this packet using the vanilla Buffer class, you would have to count up the length of the data payload beforehand. You would also need to keep track of the current "cursor" position in your Buffer so you write everything in the right places. With smart-buffer you don't have to do either of those things.
`javascript
function createLoginPacket(username, password, age, country) {
const packet = new SmartBuffer();
packet.writeUInt16LE(0x0060); // Some packet type
packet.writeStringNT(username);
packet.writeStringNT(password);
packet.writeUInt8(age);
packet.writeStringNT(country);
packet.insertUInt16LE(packet.length - 2, 2);
return packet.toArrayBuffer();
}
``
With the above function, you now can do this:javascript
const login = createLoginPacket("Josh", "secret123", 22, "United States");
// ArrayBuffer { [Uint8Contents]: <60 00 1e 00 4a 6f 73 68 00 73 65 63 72 65 74 31 32 33 00 16 55 6e 69 74 65 64 20 53 74 61 74 65 73 00>, byteLength: 34 }
`[PacketLength:2]
Notice that the value (1e 00) was inserted at position 2.
Reading back the packet we created above is just as easy:
`javascript
const reader = SmartBuffer.fromBuffer(login);
const logininfo = {
packetType: reader.readUInt16LE(),
packetLength: reader.readUInt16LE(),
username: reader.readStringNT(),
password: reader.readStringNT(),
age: reader.readUInt8(),
country: reader.readStringNT()
};
/*
{
packetType: 96, (0x0060)
packetLength: 30,
username: 'Josh',
password: 'secret123',
age: 22,
country: 'United States'
}
*/
`
There are a few different ways to construct a SmartBuffer instance.
`javascript
// Creating SmartBuffer from existing Buffer
const buff = SmartBuffer.fromBuffer(buffer); // Creates instance from buffer. (Uses default utf8 encoding)
const buff = SmartBuffer.fromBuffer(buffer, 'ascii'); // Creates instance from buffer with ascii encoding for strings.
// Creating SmartBuffer with specified internal Buffer size. (Note: this is not a hard cap, the internal buffer will grow as needed).
const buff = SmartBuffer.fromSize(1024); // Creates instance with internal Buffer size of 1024.
const buff = SmartBuffer.fromSize(1024, 'utf8'); // Creates instance with internal Buffer size of 1024, and utf8 encoding for strings.
// Creating SmartBuffer with options object. This one specifies size and encoding.
const buff = SmartBuffer.fromOptions({
size: 1024,
encoding: 'ascii'
});
// Creating SmartBuffer with options object. This one specified an existing Buffer.
const buff = SmartBuffer.fromOptions({
buff: buffer
});
// Creating SmartBuffer from a string.
const buff = SmartBuffer.fromBuffer(Buffer.from('some string', 'utf8'));
// Just want a regular SmartBuffer with all default options?
const buff = new SmartBuffer();
`
Note: SmartBuffer is fully documented with Typescript definitions as well as jsdocs so your favorite editor/IDE will have intellisense.
Table of Contents
1. Constructing
2. Numbers
1. Integers
2. Floating Points
3. Strings
1. Strings
2. Null Terminated Strings
4. ArrayBuffers
5. Uint8Arrays
6. Buffers
7. Offsets
8. Other
options` {SmartBufferOptions} An optional options object to construct a SmartBuffer with.Examples:
`javascript
const buff = new SmartBuffer();
const buff = new SmartBuffer({
size: 1024,
encoding: 'ascii'
});
`$3
- `buffer` {Buffer} The Buffer instance to wrap.
- `encoding` {string} The string encoding to use. `Default: 'utf8'`Examples:
`javascript
const someBuffer = Buffer.from('some string');
const buff = SmartBuffer.fromBuffer(someBuffer); // Defaults to utf8
const buff = SmartBuffer.fromBuffer(someBuffer, 'ascii');
`$3
- `size` {number} The size to initialize the internal Buffer.
- `encoding` {string} The string encoding to use. `Default: 'utf8'`Examples:
`javascript
const buff = SmartBuffer.fromSize(1024); // Defaults to utf8
const buff = SmartBuffer.fromSize(1024, 'ascii');
`$3
- `options` {SmartBufferOptions} The Buffer instance to wrap.`typescript
interface SmartBufferOptions {
encoding?: BufferEncoding; // Defaults to utf8
size?: number; // Defaults to 4096
buff?: Buffer;
}
`Examples:
`javascript
const buff = SmartBuffer.fromOptions({
size: 1024
};
const buff = SmartBuffer.fromOptions({
size: 1024,
encoding: 'utf8'
});
const buff = SmartBuffer.fromOptions({
encoding: 'utf8'
});const someBuff = Buffer.from('some string', 'utf8');
const buff = SmartBuffer.fromOptions({
buffer: someBuff,
encoding: 'utf8'
});
`Integers
$3
$3
- `offset` {number} Optional position to start reading data from. Default: `Auto managed offset`
- Returns {number}Read a Int8 value.
$3
$3
$3
$3
- `offset` {number} Optional position to start reading data from. Default: `Auto managed offset`
- Returns {number}Read a 16 bit integer value.
$3
$3
$3
$3
- `offset` {number} Optional position to start reading data from. Default: `Auto managed offset`
- Returns {number}Read a 32 bit integer value.
$3
$3
- `value` {number} The value to write.
- `offset` {number} An optional offset to write this value to. Default: `Auto managed offset`
- Returns {this}Write a Int8 value.
$3
$3
- `value` {number} The value to insert.
- `offset` {number} The offset to insert this data at.
- Returns {this}Insert a Int8 value.
$3
$3
$3
$3
- `value` {number} The value to write.
- `offset` {number} An optional offset to write this value to. Default: `Auto managed offset`
- Returns {this}Write a 16 bit integer value.
$3
$3
$3
$3
- `value` {number} The value to insert.
- `offset` {number} The offset to insert this data at.
- Returns {this}Insert a 16 bit integer value.
$3
$3
$3
$3
- `value` {number} The value to write.
- `offset` {number} An optional offset to write this value to. Default: `Auto managed offset`
- Returns {this}Write a 32 bit integer value.
$3
$3
$3
$3
- `value` {number} The value to insert.
- `offset` {number} The offset to insert this data at.
- Returns {this}Insert a 32 bit integer value.
Floating Point Numbers
$3
$3
- `offset` {number} Optional position to start reading data from. Default: `Auto managed offset`
- Returns {number}Read a Float value.
$3
$3
- `offset` {number} Optional position to start reading data from. Default: `Auto managed offset`
- Returns {number}Read a Double value.
$3
$3
- `value` {number} The value to write.
- `offset` {number} An optional offset to write this value to. Default: `Auto managed offset`
- Returns {this}Write a Float value.
$3
$3
- `value` {number} The value to insert.
- `offset` {number} The offset to insert this data at.
- Returns {this}Insert a Float value.
$3
$3
- `value` {number} The value to write.
- `offset` {number} An optional offset to write this value to. Default: `Auto managed offset`
- Returns {this}Write a Double value.
$3
$3
- `value` {number} The value to insert.
- `offset` {number} The offset to insert this data at.
- Returns {this}Insert a Double value.
Strings
$3
$3
$3
- `size` {number} The number of bytes to read. Default: `Reads to the end of the Buffer.`
- `encoding` {string} The string encoding to use. Default: `utf8`.Read a string value.
Examples:
`javascript
const buff = SmartBuffer.fromBuffer(Buffer.from('hello there', 'utf8'));
buff.readString(); // 'hello there'
buff.readString(2); // 'he'
buff.readString(2, 'utf8'); // 'he'
buff.readString('utf8'); // 'hello there'
`$3
$3
$3
$3
- `value` {string} The string value to write.
- `offset` {number} The offset to write this value to. Default: `Auto managed offset`
- `encoding` {string} An optional string encoding to use. Default: `utf8`Write a string value.
Examples:
`javascript
buff.writeString('hello'); // Auto managed offset
buff.writeString('hello', 2);
buff.writeString('hello', 'utf8') // Auto managed offset
buff.writeString('hello', 2, 'utf8');
`$3
- `value` {string} The string value to write.
- `offset` {number} The offset to write this value to.
- `encoding` {string} An optional string encoding to use. Default: `utf8`Insert a string value.
Examples:
`javascript
buff.insertString('hello', 2);
buff.insertString('hello', 2, 'utf8');
`Null Terminated Strings
$3
$3
- `encoding` {string} The string encoding to use. Default: `utf8`.Read a null terminated string value. (If a null is not found, it will read to the end of the Buffer).
Examples:
`javascript
const buff = SmartBuffer.fromBuffer(Buffer.from('hello\0 there', 'utf8'));
buff.readStringNT(); // 'hello'// If we called this again:
buff.readStringNT(); // ' there'
`$3
$3
$3
$3
- `value` {string} The string value to write.
- `offset` {number} The offset to write this value to. Default: `Auto managed offset`
- `encoding` {string} An optional string encoding to use. Default: `utf8`Write a null terminated string value.
Examples:
`javascript
buff.writeStringNT('hello'); // Auto managed offset
buff.writeStringNT('hello', 2); //
buff.writeStringNT('hello', 'utf8') // Auto managed offset
buff.writeStringNT('hello', 2, 'utf8');
`$3
- `value` {string} The string value to write.
- `offset` {number} The offset to write this value to.
- `encoding` {string} An optional string encoding to use. Default: `utf8`Insert a null terminated string value.
Examples:
`javascript
buff.insertStringNT('hello', 2);
buff.insertStringNT('hello', 2, 'utf8');
`ArrayBuffers
$3
- `length` {number} The number of bytes to read into an ArrayBuffer. Default: `Reads to the end of the Buffer`Read an ArrayBuffer of a specified size.
$3
- `value` {ArrayBuffer} The array buffer value to write.
- `offset` {number} An optional offset to write the value to. Default: `Auto managed offset`$3
- `value` {ArrayBuffer} The array buffer value to write.
- `offset` {number} The offset to write the value to.
$3
Read a null terminated ArrayBuffer.
$3
- `value` {ArrayBuffer} The array buffer value to write.
- `offset` {number} An optional offset to write the value to. Default: `Auto managed offset`Write a null terminated ArrayBuffer.
$3
- `value` {ArrayBuffer} The array buffer value to write.
- `offset` {number} The offset to write the value to.Insert a null terminated ArrayBuffer.
Uint8Arrays
$3
- `length` {number} The number of bytes to read into an Uint8Array. Default: `Reads to the end of the Buffer`Read an Uint8Array of a specified size.
$3
- `value` {Uint8Array} The array buffer value to write.
- `offset` {number} An optional offset to write the value to. Default: `Auto managed offset`$3
- `value` {Uint8Array} The array buffer value to write.
- `offset` {number} The offset to write the value to.
$3
Read a null terminated Uint8Array.
$3
- `value` {Uint8Array} The array buffer value to write.
- `offset` {number} An optional offset to write the value to. Default: `Auto managed offset`Write a null terminated Uint8Array.
$3
- `value` {Uint8Array} The array buffer value to write.
- `offset` {number} The offset to write the value to.Insert a null terminated Uint8Array.
Buffers
$3
- `length` {number} The number of bytes to read into a Buffer. Default: `Reads to the end of the Buffer`Read a Buffer of a specified size.
NOTE: These method only works in environments that provide a Buffer global, like Node.js. It is advised to use
readUint8Array() instead.$3
- `value` {Buffer} The buffer value to write.
- `offset` {number} An optional offset to write the value to. Default: `Auto managed offset`$3
- `value` {Buffer} The buffer value to write.
- `offset` {number} The offset to write the value to.
$3
Read a null terminated Buffer.
$3
- `value` {Buffer} The buffer value to write.
- `offset` {number} An optional offset to write the value to. Default: `Auto managed offset`Write a null terminated Buffer.
$3
- `value` {Buffer} The buffer value to write.
- `offset` {number} The offset to write the value to.Insert a null terminated Buffer.
Offsets
$3
$3
- `offset` {number} The new read offset value to set.
- Returns: `The current read offset`Gets or sets the current read offset.
Examples:
`javascript
const currentOffset = buff.readOffset; // 5buff.readOffset = 10;
console.log(buff.readOffset) // 10
`$3
$3
- `offset` {number} The new write offset value to set.
- Returns: `The current write offset`Gets or sets the current write offset.
Examples:
`javascript
const currentOffset = buff.writeOffset; // 5buff.writeOffset = 10;
console.log(buff.writeOffset) // 10
`$3
$3
- `encoding` {string} The new string encoding to set.
- Returns: `The current string encoding`Gets or sets the current string encoding.
Examples:
`javascript
const currentEncoding = buff.encoding; // 'utf8'buff.encoding = 'ascii';
console.log(buff.encoding) // 'ascii'
`Other
$3
Clear and resets the SmartBuffer instance.
$3
- Returns `Remaining data left to be read`Gets the number of remaining bytes to be read.
$3
- Returns: {Buffer}Gets the internally managed ArrayBuffer (Includes unmanaged data).
Note that if the SmartBuffer was created from a Uint8Array, then this returns that array's underlying ArrayBuffer, which might have a different byteLength than the Uint8Array because the Uint8Array might have been constructed as
new Uint8Array(buffer, byteOffset, length)!Examples:
`javascript
const ab = new ArrayBuffer(16);
const buff = SmartBuffer.fromBuffer(ab);
buff.writeString('hello');
console.log(buff.internalArrayBuffer); // ArrayBuffer { [Uint8Contents]: <68 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00>, byteLength: 16 }>
console.log(buff.internalArrayBuffer === ab); // trueconst view = new Uint8Array(ab, 2);
const buff = SmartBuffer.fromBuffer(view);
console.log(buff.internalArrayBuffer === ab); // true
`$3
- Returns: {Uint8Array}Gets the internally managed data as a Uint8Array (Includes unmanaged data).
Note that if the SmartBuffer was created from an ArrayBuffer, then this returns a Uint8Array constructed from that ArrayBuffer.
If the SmartBuffer was created from a Uint8Array instead - including a Node.js buffer - then this is returned by reference.
Examples:
`javascript
const array = new Uint8Array(16);
const buff = SmartBuffer.fromBuffer(array);
buff.writeString('hello');
console.log(buff.internalUint8Array); // Uint8Array(5) [ 104, 101, 108, 108, 111, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
console.log(buff.internalUint8Array === array); // true
`$3
- Returns: {ArrayBuffer}Gets a sliced ArrayBuffer instance of the internally managed ArrayBuffer. (Only includes managed data)
Examples:
`javascript
const buff = SmartBuffer.fromSize(16);
buff.writeString('hello');
console.log(buff.toArrayBuffer()); // ArrayBuffer { [Uint8Contents]: <68 65 6c 6c 6f>, byteLength: 5 }
`$3
- Returns: {Uint8Array}Gets a sliced Uint8Array instance of the internally managed ArrayBuffer. (Only includes managed data)
Examples:
`javascript
const buff = SmartBuffer.fromSize(16);
buff.writeString('hello');
console.log(buff.toUint8Array()); // Uint8Array(5) [ 104, 101, 108, 108, 111 ]
`$3
- Returns: {Buffer}Gets a sliced Buffer instance of the internally managed Buffer. (Only includes managed data)
NOTE: This only works in environments that provide a Buffer global, like Node.js.
Examples:
`javascript
const buff = SmartBuffer.fromSize(16);
buff.writeString('hello');
console.log(buff.toBuffer()); //
`$3
- `encoding` {string} The string encoding to use when converting to a string. Default: `utf8``Gets a string representation of all data in the SmartBuffer.
Destroys the SmartBuffer instance.
This work is licensed under the MIT license.