smart-buffer

中文文档
4.2.0发布于 2021/08/07MITTypeScriptCommonJS零依赖近 30 天下载 2.3亿

smart-buffer is a Buffer wrapper that adds automatic read & write offset tracking, string operations, data insertions, and more.

原始使用文档
文档目录96 节
  1. Breaking Changes in v4.0
  2. Looking for v3 docs?
  3. Installing:
  4. Using smart-buffer
  5. Simple Example
  6. Write vs Insert
  7. Constructing a smart-buffer
  8. Constructing
  9. constructor()
  10. constructor([options])
  11. Class Method: fromBuffer(buffer[, encoding])
  12. Class Method: fromSize(size[, encoding])
  13. Class Method: fromOptions(options)
  14. Integers
  15. buff.readInt8([offset])
  16. buff.readUInt8([offset])
  17. buff.readInt16BE([offset])
  18. buff.readInt16LE([offset])
  19. buff.readUInt16BE([offset])
  20. buff.readUInt16LE([offset])
  21. buff.readInt32BE([offset])
  22. buff.readInt32LE([offset])
  23. buff.readUInt32BE([offset])
  24. buff.readUInt32LE([offset])
  25. buff.writeInt8(value[, offset])
  26. buff.writeUInt8(value[, offset])
  27. buff.insertInt8(value, offset)
  28. buff.insertUInt8(value, offset)
  29. buff.writeInt16BE(value[, offset])
  30. buff.writeInt16LE(value[, offset])
  31. buff.writeUInt16BE(value[, offset])
  32. buff.writeUInt16LE(value[, offset])
  33. buff.insertInt16BE(value, offset)
  34. buff.insertInt16LE(value, offset)
  35. buff.insertUInt16BE(value, offset)
  36. buff.insertUInt16LE(value, offset)
  37. buff.writeInt32BE(value[, offset])
  38. buff.writeInt32LE(value[, offset])
  39. buff.writeUInt32BE(value[, offset])
  40. buff.writeUInt32LE(value[, offset])
  41. buff.insertInt32BE(value, offset)
  42. buff.insertInt32LE(value, offset)
  43. buff.insertUInt32BE(value, offset)
  44. buff.nsertUInt32LE(value, offset)
  45. Floating Point Numbers
  46. buff.readFloatBE([offset])
  47. buff.readFloatLE([offset])
  48. buff.readDoubleBE([offset])
  49. buff.readDoubleLE([offset])
  50. buff.writeFloatBE(value[, offset])
  51. buff.writeFloatLE(value[, offset])
  52. buff.insertFloatBE(value, offset)
  53. buff.insertFloatLE(value, offset)
  54. buff.writeDoubleBE(value[, offset])
  55. buff.writeDoubleLE(value[, offset])
  56. buff.insertDoubleBE(value, offset)
  57. buff.insertDoubleLE(value, offset)
  58. Strings
  59. buff.readString()
  60. buff.readString(size[, encoding])
  61. buff.readString(encoding)
  62. buff.writeString(value)
  63. buff.writeString(value[, offset])
  64. buff.writeString(value[, encoding])
  65. buff.writeString(value[, offset[, encoding]])
  66. buff.insertString(value, offset[, encoding])
  67. Null Terminated Strings
  68. buff.readStringNT()
  69. buff.readStringNT(encoding)
  70. buff.writeStringNT(value)
  71. buff.writeStringNT(value[, offset])
  72. buff.writeStringNT(value[, encoding])
  73. buff.writeStringNT(value[, offset[, encoding]])
  74. buff.insertStringNT(value, offset[, encoding])
  75. Buffers
  76. buff.readBuffer([length])
  77. buff.writeBuffer(value[, offset])
  78. buff.insertBuffer(value, offset)
  79. buff.readBufferNT()
  80. buff.writeBufferNT(value[, offset])
  81. buff.insertBufferNT(value, offset)
  82. Offsets
  83. buff.readOffset
  84. buff.readOffset(offset)
  85. buff.writeOffset
  86. buff.writeOffset(offset)
  87. buff.encoding
  88. buff.encoding(encoding)
  89. Other
  90. buff.clear()
  91. buff.remaining()
  92. buff.internalBuffer
  93. buff.toBuffer()
  94. buff.toString([encoding])
  95. buff.destroy()
  96. License

smart-buffer Build Status Coverage Status

smart-buffer is a Buffer wrapper that adds automatic read & write offset tracking, string operations, data insertions, and more.

stats

Key Features:

  • Proxies all of the Buffer write and read functions
  • Keeps track of read and write offsets automatically
  • Grows the internal Buffer as needed
  • Useful string operations. (Null terminating strings)
  • Allows for inserting values at specific points in the Buffer
  • Built in TypeScript
  • Type Definitions Provided
  • Browser Support (using Webpack/Browserify)
  • Full test coverage

Requirements:

  • Node v4.0+ is supported at this time. (Versions prior to 2.0 will work on node 0.10)

Breaking Changes in v4.0

  • Old constructor patterns have been completely removed. It's now required to use the SmartBuffer.fromXXX() factory constructors.
  • rewind(), skip(), moveTo() have been removed. (see offsets)
  • Internal private properties are now prefixed with underscores (_)
  • All writeXXX() methods that are given an offset will now overwrite data instead of insert. (see write vs insert)
  • insertXXX() methods have been added for when you want to insert data at a specific offset (this replaces the old behavior of writeXXX() when an offset was provided)

Looking for v3 docs?

Legacy documentation for version 3 and prior can be found here.

Installing:

yarn add smart-buffer

or

npm install smart-buffer

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

Using smart-buffer

// Javascript
const SmartBuffer = require('smart-buffer').SmartBuffer;

// Typescript
import { SmartBuffer, SmartBufferOptions} from 'smart-buffer';

Simple Example

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.

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.toBuffer();
}

With the above function, you now can do this:

const login = createLoginPacket("Josh", "secret123", 22, "United States");

// <Buffer 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>

Notice that the [PacketLength:2] value (1e 00) was inserted at position 2.

Reading back the packet we created above is just as easy:


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'
}
*/

Write vs Insert

In prior versions of SmartBuffer, .writeXXX(value, offset) calls would insert data when an offset was provided. In version 4, this will now overwrite the data at the offset position. To insert data there are now corresponding .insertXXX(value, offset) methods.

SmartBuffer v3:

const buff = SmartBuffer.fromBuffer(new Buffer([1,2,3,4,5,6]));
buff.writeInt8(7, 2);
console.log(buff.toBuffer())

// <Buffer 01 02 07 03 04 05 06>

SmartBuffer v4:

const buff = SmartBuffer.fromBuffer(new Buffer([1,2,3,4,5,6]));
buff.writeInt8(7, 2);
console.log(buff.toBuffer());

// <Buffer 01 02 07 04 05 06>

To insert you instead should use:

const buff = SmartBuffer.fromBuffer(new Buffer([1,2,3,4,5,6]));
buff.insertInt8(7, 2);
console.log(buff.toBuffer());

// <Buffer 01 02 07 03 04 05 06>

Note: Insert/Writing to a position beyond the currently tracked internal Buffer will zero pad to your offset.

Constructing a smart-buffer

There are a few different ways to construct a SmartBuffer instance.

// 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();

Api Reference:

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. Buffers
  5. Offsets
  6. Other

Constructing

constructor()

constructor([options])

  • options {SmartBufferOptions} An optional options object to construct a SmartBuffer with.

Examples:

const buff = new SmartBuffer();
const buff = new SmartBuffer({
    size: 1024,
    encoding: 'ascii'
});

Class Method: fromBuffer(buffer[, encoding])

  • buffer {Buffer} The Buffer instance to wrap.
  • encoding {string} The string encoding to use. Default: 'utf8'

Examples:

const someBuffer = Buffer.from('some string');
const buff = SmartBuffer.fromBuffer(someBuffer); // Defaults to utf8
const buff = SmartBuffer.fromBuffer(someBuffer, 'ascii');

Class Method: fromSize(size[, encoding])

  • size {number} The size to initialize the internal Buffer.
  • encoding {string} The string encoding to use. Default: 'utf8'

Examples:

const buff = SmartBuffer.fromSize(1024); // Defaults to utf8
const buff = SmartBuffer.fromSize(1024, 'ascii');

Class Method: fromOptions(options)

  • options {SmartBufferOptions} The Buffer instance to wrap.
interface SmartBufferOptions {
    encoding?: BufferEncoding; // Defaults to utf8
    size?: number; // Defaults to 4096
    buff?: Buffer;
}

Examples:

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

buff.readInt8([offset])

buff.readUInt8([offset])

  • offset {number} Optional position to start reading data from. Default: Auto managed offset
  • Returns {number}

Read a Int8 value.

buff.readInt16BE([offset])

buff.readInt16LE([offset])

buff.readUInt16BE([offset])

buff.readUInt16LE([offset])

  • offset {number} Optional position to start reading data from. Default: Auto managed offset
  • Returns {number}

Read a 16 bit integer value.

buff.readInt32BE([offset])

buff.readInt32LE([offset])

buff.readUInt32BE([offset])

buff.readUInt32LE([offset])

  • offset {number} Optional position to start reading data from. Default: Auto managed offset
  • Returns {number}

Read a 32 bit integer value.

buff.writeInt8(value[, offset])

buff.writeUInt8(value[, offset])

  • 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.

buff.insertInt8(value, offset)

buff.insertUInt8(value, offset)

  • value {number} The value to insert.
  • offset {number} The offset to insert this data at.
  • Returns {this}

Insert a Int8 value.

buff.writeInt16BE(value[, offset])

buff.writeInt16LE(value[, offset])

buff.writeUInt16BE(value[, offset])

buff.writeUInt16LE(value[, offset])

  • 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.

buff.insertInt16BE(value, offset)

buff.insertInt16LE(value, offset)

buff.insertUInt16BE(value, offset)

buff.insertUInt16LE(value, offset)

  • value {number} The value to insert.
  • offset {number} The offset to insert this data at.
  • Returns {this}

Insert a 16 bit integer value.

buff.writeInt32BE(value[, offset])

buff.writeInt32LE(value[, offset])

buff.writeUInt32BE(value[, offset])

buff.writeUInt32LE(value[, offset])

  • 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.

buff.insertInt32BE(value, offset)

buff.insertInt32LE(value, offset)

buff.insertUInt32BE(value, offset)

buff.nsertUInt32LE(value, offset)

  • 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

buff.readFloatBE([offset])

buff.readFloatLE([offset])

  • offset {number} Optional position to start reading data from. Default: Auto managed offset
  • Returns {number}

Read a Float value.

buff.readDoubleBE([offset])

buff.readDoubleLE([offset])

  • offset {number} Optional position to start reading data from. Default: Auto managed offset
  • Returns {number}

Read a Double value.

buff.writeFloatBE(value[, offset])

buff.writeFloatLE(value[, offset])

  • 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.

buff.insertFloatBE(value, offset)

buff.insertFloatLE(value, offset)

  • value {number} The value to insert.
  • offset {number} The offset to insert this data at.
  • Returns {this}

Insert a Float value.

buff.writeDoubleBE(value[, offset])

buff.writeDoubleLE(value[, offset])

  • 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.

buff.insertDoubleBE(value, offset)

buff.insertDoubleLE(value, offset)

  • value {number} The value to insert.
  • offset {number} The offset to insert this data at.
  • Returns {this}

Insert a Double value.

Strings

buff.readString()

buff.readString(size[, encoding])

buff.readString(encoding)

  • 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:

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'

buff.writeString(value)

buff.writeString(value[, offset])

buff.writeString(value[, encoding])

buff.writeString(value[, offset[, encoding]])

  • 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:

buff.writeString('hello'); // Auto managed offset
buff.writeString('hello', 2);
buff.writeString('hello', 'utf8') // Auto managed offset
buff.writeString('hello', 2, 'utf8');

buff.insertString(value, offset[, encoding])

  • 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:

buff.insertString('hello', 2);
buff.insertString('hello', 2, 'utf8');

Null Terminated Strings

buff.readStringNT()

buff.readStringNT(encoding)

  • 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:

const buff = SmartBuffer.fromBuffer(Buffer.from('hello\0 there', 'utf8'));
buff.readStringNT(); // 'hello'

// If we called this again:
buff.readStringNT(); // ' there'

buff.writeStringNT(value)

buff.writeStringNT(value[, offset])

buff.writeStringNT(value[, encoding])

buff.writeStringNT(value[, offset[, encoding]])

  • 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:

buff.writeStringNT('hello'); // Auto managed offset   <Buffer 68 65 6c 6c 6f 00>
buff.writeStringNT('hello', 2); // <Buffer 00 00 68 65 6c 6c 6f 00>
buff.writeStringNT('hello', 'utf8') // Auto managed offset
buff.writeStringNT('hello', 2, 'utf8');

buff.insertStringNT(value, offset[, encoding])

  • 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:

buff.insertStringNT('hello', 2);
buff.insertStringNT('hello', 2, 'utf8');

Buffers

buff.readBuffer([length])

  • 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.

buff.writeBuffer(value[, offset])

  • value {Buffer} The buffer value to write.
  • offset {number} An optional offset to write the value to. Default: Auto managed offset

buff.insertBuffer(value, offset)

  • value {Buffer} The buffer value to write.
  • offset {number} The offset to write the value to.

buff.readBufferNT()

Read a null terminated Buffer.

buff.writeBufferNT(value[, offset])

  • 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.

buff.insertBufferNT(value, offset)

  • value {Buffer} The buffer value to write.
  • offset {number} The offset to write the value to.

Insert a null terminated Buffer.

Offsets

buff.readOffset

buff.readOffset(offset)

  • offset {number} The new read offset value to set.
  • Returns: The current read offset

Gets or sets the current read offset.

Examples:

const currentOffset = buff.readOffset; // 5

buff.readOffset = 10;

console.log(buff.readOffset) // 10

buff.writeOffset

buff.writeOffset(offset)

  • offset {number} The new write offset value to set.
  • Returns: The current write offset

Gets or sets the current write offset.

Examples:

const currentOffset = buff.writeOffset; // 5

buff.writeOffset = 10;

console.log(buff.writeOffset) // 10

buff.encoding

buff.encoding(encoding)

  • encoding {string} The new string encoding to set.
  • Returns: The current string encoding

Gets or sets the current string encoding.

Examples:

const currentEncoding = buff.encoding; // 'utf8'

buff.encoding = 'ascii';

console.log(buff.encoding) // 'ascii'

Other

buff.clear()

Clear and resets the SmartBuffer instance.

buff.remaining()

  • Returns Remaining data left to be read

Gets the number of remaining bytes to be read.

buff.internalBuffer

  • Returns: {Buffer}

Gets the internally managed Buffer (Includes unmanaged data).

Examples:

const buff = SmartBuffer.fromSize(16);
buff.writeString('hello');
console.log(buff.InternalBuffer); // <Buffer 68 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00>

buff.toBuffer()

  • Returns: {Buffer}

Gets a sliced Buffer instance of the internally managed Buffer. (Only includes managed data)

Examples:

const buff = SmartBuffer.fromSize(16);
buff.writeString('hello');
console.log(buff.toBuffer()); // <Buffer 68 65 6c 6c 6f>

buff.toString([encoding])

  • encoding {string} The string encoding to use when converting to a string. Default: utf8
  • Returns {string}

Gets a string representation of all data in the SmartBuffer.

buff.destroy()

Destroys the SmartBuffer instance.

License

This work is licensed under the MIT license.

版本与发布记录

smart-buffer 共发布 32 个版本,首次发布于 2013/11/03;过去 12 个月发布了 0 个版本。

版本发布日期距今
4.2.0latest2021/08/075 年前
4.1.02019/07/247 年前
4.0.22019/01/247 年前
4.0.12017/11/128 年前
4.0.02017/10/219 年前
4.0.0-beta.1beta2017/06/259 年前

关于 smart-buffer 的常见问题

smart-buffer 是什么?

smart-buffer is a Buffer wrapper that adds automatic read & write offset tracking, string operations, data insertions, and more.

如何安装 smart-buffer?

在项目目录运行 npm install smart-buffer,或使用 pnpm add / yarn add / bun add。

smart-buffer 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

smart-buffer 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

smart-buffer 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 6.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

smart-buffer 可以商用吗?

smart-buffer 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

smart-buffer 的下载量有多少?

根据 npm 官方下载统计,smart-buffer 在 2026/10/05 – 2026/11/03 这 30 天内被下载 226,118,707 次,日均约 7,537,290 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

smart-buffer 还在维护吗?

最新版本 4.2.0 发布于 2021/08/07(5 年前);至今共发布 32 个版本,其中过去 12 个月发布了 0 个;首次发布于 2013/11/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。