'use strict'; const test = require('node:test'), assert = require('node:assert/strict'), http = require('node:http'); const { readBody } = require('../server/middleware/body'); // 真实 HTTP:服务端用 readBody 解析后原样回显;客户端按奇数字节分段写出,让多字节汉字落在块边界上。 async function echoServer(t) { const server = http.createServer(async (req, res) => { try { const body = await readBody(req); res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(body)); } catch (e) { res.writeHead(e.status || 500, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify({ error: e.message })); } }); await new Promise(r => server.listen(0, '127.0.0.1', r)); t.after(() => new Promise(r => server.close(r))); return server.address().port; } function send(port, payload, pieceSize = 1001) { return new Promise((resolve, reject) => { const req = http.request({ host: '127.0.0.1', port, method: 'POST', path: '/' }, res => { const chunks = []; res.on('data', c => chunks.push(c)); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(Buffer.concat(chunks).toString('utf8')) }), ); }); req.on('error', reject); const bytes = Buffer.from(payload); for (let i = 0; i < bytes.length; i += pieceSize) req.write(bytes.subarray(i, i + pieceSize)); req.end(); }); } test('约72KB中文JSON请求体经HTTP分块传输后原样还原', async t => { const port = await echoServer(t); const note = '足金手链金价工费备注,'.repeat(2200); const payload = JSON.stringify({ note, lines: [{ name: '古法金镯子(新款)', note: note.slice(0, 1000) }] }); assert.ok(Buffer.byteLength(payload) > 72000 && Buffer.byteLength(payload) < 300000); for (const pieceSize of [1001, 16384, 65537]) { const r = await send(port, payload, pieceSize); assert.equal(r.status, 200); assert.equal(r.body.note, note); assert.ok(!JSON.stringify(r.body).includes('�')); assert.deepEqual(r.body, JSON.parse(payload)); } }); test('请求体上限、非JSON与空请求体的处理不变', async t => { const port = await echoServer(t); const atLimit = JSON.stringify({ s: '汉'.repeat(99995) }); assert.equal(Buffer.byteLength(atLimit), 299993); assert.equal((await send(port, atLimit)).status, 200); const over = JSON.stringify({ s: '汉'.repeat(99998) }); assert.equal(Buffer.byteLength(over), 300002); assert.deepEqual(await send(port, over), { status: 413, body: { error: '内容过大' } }); assert.deepEqual(await send(port, '{"a":'), { status: 400, body: { error: '请求内容不是有效JSON' } }); assert.deepEqual(await send(port, ''), { status: 200, body: {} }); });