function deepEqual(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
// Case 1: Buffer.alloc / allocUnsafe / allocUnsafeSlow / Buffer.from & character encodings
const allocZero = Buffer.alloc(4);
const allocFilled = Buffer.alloc(4, 1);
const allocUnsafeFilled = Buffer.allocUnsafe(4).fill(0x2a);
const allocSlowFilled = Buffer.allocUnsafeSlow(4).fill(0x05);
const fromArray = Buffer.from([1, 2, 3]);
const ab = new ArrayBuffer(4);
const viewFromAb = Buffer.from(ab);
viewFromAb[0] = 0x41;
const sharedFirstByte = new Uint8Array(ab)[0];
const copiedBuf = Buffer.from(fromArray);
copiedBuf[0] = 99;
const asciiBuf = Buffer.from('node24', 'ascii');
const utf8Accent = Array.from(Buffer.from('tést', 'utf8'));
const latin1Accent = Array.from(Buffer.from('tést', 'latin1'));
const utf16Hex = Buffer.from('AB', 'utf16le').toString('hex');
const actual1 = {
allocZero: Array.from(allocZero),
allocFilled: Array.from(allocFilled),
allocUnsafeFilled: Array.from(allocUnsafeFilled),
allocSlowFilled: Array.from(allocSlowFilled),
fromArrayUnchanged: Array.from(fromArray),
sharedFirstByte,
hex: asciiBuf.toString('hex'),
base64: asciiBuf.toString('base64'),
utf8Accent,
latin1Accent,
utf16Hex,
};
const expected1 = {
allocZero: [0, 0, 0, 0],
allocFilled: [1, 1, 1, 1],
allocUnsafeFilled: [42, 42, 42, 42],
allocSlowFilled: [5, 5, 5, 5],
fromArrayUnchanged: [1, 2, 3],
sharedFirstByte: 65,
hex: '6e6f64653234',
base64: 'bm9kZTI0',
utf8Accent: [0x74, 0xc3, 0xa9, 0x73, 0x74],
latin1Accent: [0x74, 0xe9, 0x73, 0x74],
utf16Hex: '41004200',
};
// Case 2: buf.write, buf.length, buf.toString, buf.toJSON & JSON roundtrip
const wBuf = Buffer.alloc(256);
const writtenBytes = wBuf.write('mbsky-node-buf');
const alphaBuf = Buffer.alloc(26);
for (let i = 0; i < 26; i += 1) {
alphaBuf[i] = i + 97;
}
const jsonSrc = Buffer.from([1, 2, 3, 4, 5]);
const jsonStr = JSON.stringify(jsonSrc);
const restored = JSON.parse(jsonStr, (_, value) =>
value && value.type === 'Buffer' ? Buffer.from(value.data) : value,
);
const actual2 = {
allocLength: wBuf.length,
writtenBytes,
writtenSlice: wBuf.toString('utf8', 0, writtenBytes),
alphaFull: alphaBuf.toString('ascii'),
alphaAscii5: alphaBuf.toString('ascii', 0, 5),
alphaUtf85: alphaBuf.toString('utf8', 0, 5),
alphaDefault5: alphaBuf.toString(undefined, 0, 5),
jsonStr,
restoredIsBuffer: Buffer.isBuffer(restored),
restoredEquals: restored.equals(jsonSrc),
};
const expected2 = {
allocLength: 256,
writtenBytes: 14,
writtenSlice: 'mbsky-node-buf',
alphaFull: 'abcdefghijklmnopqrstuvwxyz',
alphaAscii5: 'abcde',
alphaUtf85: 'abcde',
alphaDefault5: 'abcde',
jsonStr: '{"type":"Buffer","data":[1,2,3,4,5]}',
restoredIsBuffer: true,
restoredEquals: true,
};
// Case 3: Buffer.concat, compare, equals, copy, subarray/slice shared memory
const c1 = Buffer.from('蓝色天空');
const c2 = Buffer.from('-Node');
const merged = Buffer.concat([c1, c2]);
const mergedTruncated = Buffer.concat([c1, c2], 12);
const cmpBefore = Buffer.from('ABC').compare(Buffer.from('ABCD'));
const cmpEqual = Buffer.from('ABC').compare(Buffer.from('ABC'));
const cmpAfter = Buffer.from('ABD').compare(Buffer.from('ABC'));
const target = Buffer.from('abcdefghijkl');
const insert = Buffer.from('NODEJS');
const bytesCopied = insert.copy(target, 2);
const orig = Buffer.from('abcdef');
const sub = orig.subarray(0, 2);
sub[0] = 0x5a; // 'Z'
const actual3 = {
mergedText: merged.toString('utf8'),
mergedTruncatedText: mergedTruncated.toString('utf8'),
cmpSigns: [Math.sign(cmpBefore), Math.sign(cmpEqual), Math.sign(cmpAfter)],
bytesCopied,
afterCopy: target.toString('utf8'),
subText: sub.toString('utf8'),
origMutatedBySub: orig.toString('utf8'),
};
const expected3 = {
mergedText: '蓝色天空-Node',
mergedTruncatedText: '蓝色天空',
cmpSigns: [-1, 0, 1],
bytesCopied: 6,
afterCopy: 'abNODEJSijkl',
subText: 'Zb',
origMutatedBySub: 'Zbcdef',
};
// Case 4: Binary endian integer & float read/write + fill & index access
const le6 = Buffer.alloc(6);
le6.writeUIntLE(0x1234567890ab, 0, 6);
const be6 = Buffer.alloc(6);
be6.writeUIntBE(0x1234567890ab, 0, 6);
const numBuf = Buffer.alloc(18);
numBuf.writeInt16LE(-1234, 0);
numBuf.writeInt32BE(0x01020304, 2);
numBuf.writeFloatLE(1.5, 6);
numBuf.writeDoubleBE(3.25, 10);
const fillBuf = Buffer.alloc(5, 0);
fillBuf.fill(0x7f, 1, 4);
const actual4 = {
le6Hex: le6.toString('hex'),
be6Hex: be6.toString('hex'),
readUIntLE: le6.readUIntLE(0, 6),
readUIntBE: be6.readUIntBE(0, 6),
readInt16LE: numBuf.readInt16LE(0),
readInt32BE: numBuf.readInt32BE(2),
readFloatLE: numBuf.readFloatLE(6),
readDoubleBE: numBuf.readDoubleBE(10),
fillBytes: Array.from(fillBuf),
};
const expected4 = {
le6Hex: 'ab9078563412',
be6Hex: '1234567890ab',
readUIntLE: 0x1234567890ab,
readUIntBE: 0x1234567890ab,
readInt16LE: -1234,
readInt32BE: 0x01020304,
readFloatLE: 1.5,
readDoubleBE: 3.25,
fillBytes: [0, 127, 127, 127, 0],
};
// Case 5: Multi-byte UTF-8 byte length vs string length & partial write safety
const zhStr = '蓝色天空';
const zhBuf = Buffer.from(zhStr, 'utf8');
const smallBuf = Buffer.alloc(5); // can only hold 1 Chinese char (3 bytes), refuses partial 2nd char
const partialWritten = smallBuf.write(zhStr, 0, 'utf8');
const actual5 = {
stringLength: zhStr.length,
bufferByteLength: zhBuf.length,
partialWritten,
partialDecoded: smallBuf.toString('utf8', 0, partialWritten),
};
const expected5 = {
stringLength: 4,
bufferByteLength: 12,
partialWritten: 3,
partialDecoded: '蓝',
};
const cases = [
{ name: 'alloc_from_and_encodings', passed: deepEqual(actual1, expected1), expected: expected1, actual: actual1 },
{ name: 'write_tostring_length_and_json', passed: deepEqual(actual2, expected2), expected: expected2, actual: actual2 },
{ name: 'concat_compare_equals_copy_slice', passed: deepEqual(actual3, expected3), expected: expected3, actual: actual3 },
{ name: 'endian_int_and_float_rw', passed: deepEqual(actual4, expected4), expected: expected4, actual: actual4 },
{ name: 'utf8_byte_length_and_safe_write', passed: deepEqual(actual5, expected5), expected: expected5, actual: actual5 },
];
console.log(JSON.stringify({ version: process.version, cases }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Node.js v24.22.3 本地运行环境。
入口文件:projects/nodejs-buffer-lab/explore-buffer.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-buffer.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1042.zip