diff --git a/__test__/encode.test.ts b/__test__/encode.test.ts index 8ea6d06..965c83a 100644 --- a/__test__/encode.test.ts +++ b/__test__/encode.test.ts @@ -91,18 +91,16 @@ describe('dictionary', () => { // bittorrent 编码测试 test('encode complex dictionary', () => { const torrentStructure = { - announce: 'https://www.github.com', - 'created by': 'sloaix-node-bencode', - 'creation date': Math.floor(Date.now() / 1000), - info: { - name: 'hello.txt', - 'piece length': 16 * 1024, - length: 5, - pieces: new Uint8Array([ - 170, 244, 198, 29, 220, 197, 232, 162, 218, 190, 222, 15, 59, 72, 44, 217, 174, 169, 67, 77 - ]) - } + pieces: new Uint8Array([ + 170, 244, 198, 29, 220, 197, 232, 162, 218, 190, 222, 15, 59, 72, 44, 217, 174, 169, 67, 77 + ]) } - console.log(Buffer.from(encoder.encode(torrentStructure)).toString('hex')) + + const expectValue = new Uint8Array([ + 100, 54, 58, 112, 105, 101, 99, 101, 115, 50, 48, 58, 170, 244, 198, 29, 220, 197, 232, 162, 218, 190, 222, 15, + 59, 72, 44, 217, 174, 169, 67, 77, 101 + ]) + + expect(encoder.encode(torrentStructure)).toStrictEqual(expectValue) }) }) diff --git a/package.json b/package.json index a9286f5..8172215 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sloaix-node-bencode", - "version": "0.1.5", + "version": "0.1.6", "description": "Bencode encoding and decoding, with both library and CLI versions available. The CLI version can decode bencode-formatted data from files or strings and output the result in JSON format.", "keywords": [ "bencode", diff --git a/src/encoder.ts b/src/encoder.ts index 3ff0663..b587d17 100644 --- a/src/encoder.ts +++ b/src/encoder.ts @@ -34,31 +34,28 @@ export class Bencoder { /** * 编码字节字符串 - * @param byteString 字节字符串 + * @param bufferString 字节字符串 * * 支持编码空字符串,例如 0: * 但不支持null或者undefined */ - private encodeByteString(byteString: BencodeString): Uint8Array { - if (byteString === null || byteString === undefined) { + private encodeByteString(bufferString: BencodeString): Uint8Array { + if (bufferString === null || bufferString === undefined) { throw new Error("undefined or null string isn't be supported to be encode") } - // 将除string外非Buffer类型的数据转换为Buffer - if (byteString instanceof Uint8Array) { - byteString = Buffer.from(byteString) + // 如果不是Buffer,则转换为Buffer + if (!(bufferString instanceof Buffer)) { + bufferString = Buffer.from(bufferString) } - // 将Buffer类型的数据转换为字节字符串 - if (byteString instanceof Buffer) { - byteString = byteString.toString('utf-8') - } + // 字符串的编码格式为:字符串的长度 + ':' + 字符串,例如:4:spam - // 字符串的编码格式为:字符串的长度 + ':' + 字符串 - // 例如:4:spam - const buffers: Uint8Array[] = [this.te.encode(`${byteString.toString().length}:`)] + // 编码字符串的长度 + const buffers: Uint8Array[] = [this.te.encode(`${bufferString.length}:`)] - buffers.push(Buffer.from(byteString)) + // 编码字符串内容 + buffers.push(bufferString) return Uint8Array.from(Buffer.concat(buffers)) }