Node.js 逐行读取库存清单:用 for await 做可定位的 TSV 校验
仓库系统导出的清单,常常不是复杂的数据库备份,而是一行一条、制表符分列的小文本。真正容易出错的地方也不在读取文件:第一行带了 BOM、Windows 换行混进来、数量写成了 01、坏记录后面还有好记录。这里实现一个只读校验器,让这些问题变成可定位、可测试的结果。
本文面向 Node.js 24,全部代码在 Linux、Node.js v24.19.0 上实际运行,不依赖 npm 包。程序只检查文件,不修改库存、不联网,也不执行输入中的任何命令。它适合来源可控的本地批量清单,不是面向匿名上传的安全解析服务。
图:原创 AI 生成概念插图,表达逐行检查与错误分流,不代表运行界面或内存保证。
一、先写清楚输入契约
输入为 UTF-8 文本,无表头,每条记录恰好三列:id、quantity、label,中间只能使用真实制表符。这里没有 CSV 式引号或转义规则,标签内也不能包含制表符或换行。宁可拒绝一条有歧义的记录,也不靠猜测把坏数据修成“看起来正常”。
id 为 1~32 个字符,以大写英文字母开头,后面仅允许大写字母、数字、下划线和连字符。
quantity 是 0~1000000 的十进制整数;允许 0,不接受负号、加号、前导零、小数、科学计数法或外围空格。
label 为 1~80 个 Unicode 码点,可以包含中文和内部空格,但不接受首尾空白、控制字符、BOM 或替换字符 U+FFFD。码点数不等同于屏幕上看到的字形数。
只移除文件开头的一个 BOM;只有长度为零的行算空行。空格行、制表符行不能被静默跳过。
这份契约故意不检查 id 唯一性,也不累计库存数量。重复编号是否应合并,属于业务规则;直接维护一个无限增长的编号集合,还会改变内存模型。输出中的 valid 仅表示格式合格,不表示库存已入库。
二、保留物理行号,不先 trim 整行
每读到一行就先增加行号,再处理 BOM 和空行。因此第三行错误就是第三行,不会因为前面有空行而错位。不要对整行调用 trim():它可能吞掉末尾制表符,使“第三列为空”变成另一个问题,也会悄悄掩盖不合法的外围空格。
readline 识别 LF、CR 和 CRLF,末行没有换行也能产出记录;crlfDelay: Infinity 让跨分块的 CRLF 仍视为一个换行。创建接口后应立刻进入异步循环,中间不插入其他 await。依据是 官方异步迭代说明及逐行读取示例。
三、完整实现:解析与读取分开
把下面内容保存为 inventory.mjs。parseRecord 只负责单行契约,便于独立测试;scanInventory 负责读取和统计。每条坏记录只报告最先发现的问题,并最多保留二十条错误样本,但 invalid 仍统计全部坏记录。错误中不回显原始标签,避免控制内容污染日志。
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
import { finished } from 'node:stream/promises';
export function parseRecord(line) {
const fields = line.split('\t');
if (fields.length !== 3) return { code: 'FIELDS' };
const [id, quantityText, label] = fields;
if (!/^[A-Z][A-Z0-9_-]{0,31}$/.test(id)) return { code: 'ID' };
const quantity = Number(quantityText);
if (!/^(0|[1-9][0-9]*)$/.test(quantityText)
|| !Number.isSafeInteger(quantity) || quantity > 1_000_000) {
return { code: 'QUANTITY' };
}
if (label.length === 0 || label !== label.trim()
|| [...label].length > 80
|| /[\u0000-\u001f\u007f-\u009f\uFEFF\uFFFD]/u.test(label)) {
return { code: 'LABEL' };
}
return { record: { id, quantity, label } };
}
// This function owns input and closes it, including on failure.
export async function scanInventory(input, {
maxLineBytes = 4096, maxErrors = 20,
} = {}) {
const report = { lines: 0, blank: 0, valid: 0, invalid: 0, errors: [] };
let ioError;
let rl;
const onError = (error) => {
ioError ??= error;
rl?.close();
};
input.on('error', onError);
// Attach a rejection handler immediately, not after the read loop.
const completion = finished(input, { cleanup: true }).then(
() => null,
(error) => {
onError(error);
return error;
},
);
try {
if (!Number.isSafeInteger(maxLineBytes) || maxLineBytes < 1
|| !Number.isSafeInteger(maxErrors) || maxErrors < 0) {
throw new RangeError('Invalid limits');
}
input.setEncoding('utf8');
rl = createInterface({ input, crlfDelay: Infinity, terminal: false });
rl.on('error', onError);
// Do not insert an await between createInterface and this loop.
for await (let line of rl) {
if (ioError) throw ioError;
report.lines += 1;
if (report.lines === 1 && line.startsWith('\uFEFF')) line = line.slice(1);
if (line === '') {
report.blank += 1;
continue;
}
// A validation rule, NOT an upstream allocation / memory bound.
const result = Buffer.byteLength(line, 'utf8') > maxLineBytes
? { code: 'LINE_BYTES' } : parseRecord(line);
if (result.code) {
report.invalid += 1;
if (report.errors.length < maxErrors) {
report.errors.push({ line: report.lines, code: result.code });
}
} else {
report.valid += 1;
}
}
} finally {
rl?.close();
input.destroy();
const completionError = await completion;
ioError ??= completionError;
input.off('error', onError);
rl?.off('error', onError);
}
if (ioError) throw ioError;
return report;
}
export function validateFile(path, options) {
return scanInventory(createReadStream(path), options);
}不要只给 for await 外面套一个 catch 就结束。官方文档提醒,不应依赖异步迭代器转发输入流错误。实现同时监听输入流与 readline 的 error,记录失败并关闭读取接口;finished 的拒绝处理立即注册,也覆盖没有正常结束就关闭的流。最后销毁输入、等待结束、移除监听器,读取失败时不返回半份成功统计。资源收尾参考 finished 文档和文件读取流文档。
这里的扫描函数接管传入流的生命周期,调用后不能再拿同一条流继续读。字符解码使用 UTF-8;把 U+FFFD 列为非法标签字符是本例的保守策略,不是通用的严格 UTF-8 解码器,也会拒绝原本就含该字符的标签。
错误码按检查顺序解释:LINE_BYTES 是行长超限,FIELDS 是列数不对,ID 是编号非法,QUANTITY 是数量非法,LABEL 是标签非法。一行可能同时违反多个规则,但这里只保留首个原因。这样输出简单且稳定;修复一轮后再次运行,可能发现同一行的下一处问题,这不是统计不一致。
正常完成时,lines 等于 blank、valid、invalid 三者之和。errors 只是前若干条问题的样本,不应拿数组长度当作错误总数。空文件或只有空行的文件返回成功,是因为没有违反本例的行级契约;若业务要求至少一条库存记录,应在汇总阶段另加规则,而不是偷偷改变空行的定义。
四、4096 字节规则不是硬内存上限
关键限制:readline 得到完整一行后,我们才检查长度。默认上限为去掉首个 BOM 和行结束符后的 4096 个 UTF-8 字节,不是 JavaScript 的字符串长度。如果文件只有一条数百兆、迟迟不换行的记录,内部仍可能先把它拼起来,不能宣称此代码可以阻止内存耗尽。这个判断可在 Node.js 对应版本源码的行缓冲逻辑中核对。
若输入不可信,应在解码、组行之前按字节统计并强制终止超长行,或者换用具备明确限制的解析层。调小 highWaterMark 只影响分块,不等于限定一整行。本文保留这个边界,而不是用一个事后检查冒充防护。我们的收益是不用主动把整份文件和全部错误保存成数组,并非恒定内存的承诺。
五、命令行要区分数据错误和读取失败
另存为 inventory-cli.mjs。退出码 0 表示全部非空记录合格,1 表示扫描完成但存在坏记录,2 表示参数或读取失败。前两种输出 JSON 摘要到标准输出;第三种把诊断写到标准错误,且不输出成功摘要。调用方应先看退出码,不能仅凭文件里有一个 valid 字段就决定继续导入。
import { validateFile } from './inventory.mjs';
if (process.argv.length !== 3) {
console.error('Usage: node inventory-cli.mjs <inventory.tsv>');
process.exitCode = 2;
} else {
try {
const report = await validateFile(process.argv[2]);
console.log(JSON.stringify(report));
process.exitCode = report.invalid === 0 ? 0 : 1;
} catch (error) {
console.error(JSON.stringify({
error: 'READ_FAILED', code: error.code ?? 'UNKNOWN',
}));
process.exitCode = 2;
}
}为避免复制网页时把制表符变成空格,保存下面的 create-sample.mjs,再运行它生成样例。样例包含 BOM、CRLF、空行、错误数量和无换行的末行。
import { writeFileSync } from 'node:fs';
writeFileSync('stock.tsv', '\uFEFFA\t2\t蓝色标签\r\n\r\nB\t01\tRed\r\nC\t3\tGreen');node create-sample.mjs node inventory-cli.mjs stock.tsv
实际输出如下,进程退出码为 1。错误落在物理第三行,而第四行仍被检查:
{"lines":4,"blank":1,"valid":2,"invalid":1,"errors":[{"line":3,"code":"QUANTITY"}]}六、把边界写成可运行测试
将下列内容保存为 inventory.test.mjs,与两个实现文件放在同一目录。测试既直接检查字段规则,也把 CRLF 和中文拆成多个输入块,还真实启动 CLI 子进程验证退出码。测试中的子进程只运行固定脚本,参数以数组传入,不把清单内容交给 shell。
import test from 'node:test';
import assert from 'node:assert/strict';
import { Readable } from 'node:stream';
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { spawnSync } from 'node:child_process';
import { parseRecord, scanInventory, validateFile } from './inventory.mjs';
const scan = (text, options) => scanInventory(Readable.from([text]), options);
const cli = fileURLToPath(new URL('./inventory-cli.mjs', import.meta.url));
const run = (...args) => spawnSync(process.execPath, [cli, ...args], {
encoding: 'utf8', timeout: 5000,
});
async function fixture(t, content) {
const dir = await mkdtemp(join(tmpdir(), 'inventory-'));
t.after(() => rm(dir, { recursive: true, force: true }));
const file = join(dir, 'stock.tsv');
await writeFile(file, content);
return { dir, file };
}
test('valid Chinese label and zero quantity', () => {
assert.deepEqual(parseRecord('P_1\t0\t蓝色标签'), {
record: { id: 'P_1', quantity: 0, label: '蓝色标签' },
});
});
test('BOM is removed only from the first physical line', async () => {
const r = await scan('\uFEFFA\t1\tBlue\n\uFEFFB\t2\tRed');
assert.equal(r.valid, 1);
assert.deepEqual(r.errors, [{ line: 2, code: 'ID' }]);
});
test('CRLF split over chunks counts as one newline', async () => {
const r = await scanInventory(Readable.from(['A\t1\tBlue\r', '\nB\t2\tRed\r\n']));
assert.equal(r.lines, 2);
assert.equal(r.valid, 2);
});
test('bare CR is also a recognized newline', async () => {
assert.equal((await scan('A\t1\tBlue\rB\t2\tRed')).valid, 2);
});
test('empty file has no lines', async () => {
assert.deepEqual(await scan(''), {
lines: 0, blank: 0, valid: 0, invalid: 0, errors: [],
});
});
test('blank lines retain physical error locations', async () => {
const r = await scan('\nA\t1\tBlue\n\nbad\n');
assert.equal(r.lines, 4);
assert.equal(r.blank, 2);
assert.deepEqual(r.errors, [{ line: 4, code: 'FIELDS' }]);
});
test('whitespace-only input is not silently skipped', async () => {
const r = await scan(' \n\t\t\n');
assert.equal(r.blank, 0);
assert.equal(r.invalid, 2);
});
test('last record does not require a newline', async () => {
assert.equal((await scan('A\t1\tBlue')).valid, 1);
});
test('missing or extra fields are rejected', () => {
for (const line of ['A\t1', 'A\t1\tBlue\textra']) {
assert.equal(parseRecord(line).code, 'FIELDS');
}
});
test('ID grammar and length are enforced', () => {
for (const id of ['a', '1A', ' A', 'A'.repeat(33)]) {
assert.equal(parseRecord(`${id}\t1\tBlue`).code, 'ID');
}
assert.ok(parseRecord(`${'A'.repeat(32)}\t1\tBlue`).record);
});
test('noncanonical and out-of-range quantities are rejected', () => {
for (const q of ['', '-1', '+1', '01', '1.0', '1e2', ' 1', '1000001', '9007199254740992']) {
assert.equal(parseRecord(`A\t${q}\tBlue`).code, 'QUANTITY', q);
}
assert.equal(parseRecord('A\t1000000\tBlue').record.quantity, 1_000_000);
});
test('label whitespace, controls, BOM and replacement character are rejected', () => {
for (const label of ['', ' Blue', 'Blue ', 'B\u0000', 'B\u0085', 'B\uFEFF', 'B\uFFFD']) {
assert.equal(parseRecord(`A\t1\t${label}`).code, 'LABEL');
}
});
test('label size counts code points, not UTF-16 units', () => {
assert.ok(parseRecord(`A\t1\t${'😀'.repeat(80)}`).record);
assert.equal(parseRecord(`A\t1\t${'😀'.repeat(81)}`).code, 'LABEL');
});
test('line limit uses UTF-8 bytes, excluding first BOM and line terminator', async () => {
const text = '\uFEFFA\t1\t中\r\n';
assert.equal((await scan(text, { maxLineBytes: 7 })).valid, 1);
assert.deepEqual((await scan(text, { maxLineBytes: 6 })).errors,
[{ line: 1, code: 'LINE_BYTES' }]);
});
test('error sample is capped while the full invalid count remains', async () => {
const r = await scan('bad\nbad\nbad\nA\t1\tBlue', { maxErrors: 2 });
assert.equal(r.invalid, 3);
assert.equal(r.errors.length, 2);
assert.equal(r.valid, 1);
});
test('duplicate IDs are accepted: this is not a uniqueness checker', async () => {
assert.equal((await scan('A\t1\tBlue\nA\t2\tRed')).valid, 2);
});
test('UTF-8 characters split across byte chunks are reconstructed', async () => {
const bytes = Buffer.from('A\t1\t中文\n');
const chunks = [...bytes].map((byte) => Buffer.from([byte]));
assert.equal((await scanInventory(Readable.from(chunks))).valid, 1);
});
test('invalid UTF-8 replacement does not pass label validation', async () => {
const bytes = Buffer.concat([Buffer.from('A\t1\t'), Buffer.from([0xff])]);
assert.equal((await scanInventory(Readable.from([bytes]))).errors[0].code, 'LABEL');
});
test('source error before data rejects and destroys input', async () => {
const input = new Readable({ read() { this.destroy(new Error('disk failed')); } });
await assert.rejects(scanInventory(input), /disk failed/);
assert.equal(input.destroyed, true);
});
test('source failure after a valid record never becomes success', async () => {
const input = Readable.from((async function* () {
yield 'A\t1\tBlue\n';
await new Promise((resolve) => setImmediate(resolve));
throw new Error('late disk failure');
})());
await assert.rejects(scanInventory(input), /late disk failure/);
});
test('missing file rejects with ENOENT', async (t) => {
const { dir } = await fixture(t, '');
await assert.rejects(validateFile(join(dir, 'absent.tsv')), { code: 'ENOENT' });
});
test('CLI success: exit 0 and summary on stdout', async (t) => {
const { file } = await fixture(t, 'A\t1\tBlue\n');
const r = run(file);
assert.equal(r.status, 0);
assert.equal(r.stderr, '');
assert.equal(JSON.parse(r.stdout).valid, 1);
});
test('CLI malformed records: exit 1 and all lines inspected', async (t) => {
const { file } = await fixture(t, 'bad\nA\t1\tBlue\n');
const r = run(file);
assert.equal(r.status, 1);
assert.equal(r.stderr, '');
assert.equal(JSON.parse(r.stdout).valid, 1);
assert.equal(JSON.parse(r.stdout).invalid, 1);
});
test('CLI missing file: exit 2, no success summary', async (t) => {
const { dir } = await fixture(t, '');
const r = run(join(dir, 'absent.tsv'));
assert.equal(r.status, 2);
assert.equal(r.stdout, '');
assert.equal(JSON.parse(r.stderr).code, 'ENOENT');
});
test('CLI argument failures return exit 2', () => {
for (const args of [[], ['one', 'two']]) {
const r = run(...args);
assert.equal(r.status, 2);
assert.equal(r.stdout, '');
assert.match(r.stderr, /^Usage:/);
}
});
test('premature close without an error event rejects instead of hanging', async () => {
const input = new Readable({ read() { this.destroy(); } });
await assert.rejects(scanInventory(input), { code: 'ERR_STREAM_PREMATURE_CLOSE' });
});
test('a BOM-only first line is a blank line', async () => {
const r = await scan('\uFEFF\nA\t1\tBlue\n');
assert.equal(r.lines, 2);
assert.equal(r.blank, 1);
assert.equal(r.valid, 1);
});
test('invalid limits reject and still release the owned input', async () => {
const input = Readable.from(['A\t1\tBlue']);
await assert.rejects(scanInventory(input, { maxLineBytes: 0 }), RangeError);
assert.equal(input.destroyed, true);
});node --test --test-reporter=tap inventory.test.mjs
本次实测为 28 项通过、0 项失败;另有七次独立 CLI 检查,覆盖合法文件、坏记录、超长行、缺失文件、目录误传、缺参数和多参数。目录误传在本次 Linux 环境返回 EISDIR,不把这一具体平台结果推广到所有系统。测试入口参见 Node.js 官方测试运行器文档。
# tests 28 # pass 28 # fail 0 # cancelled 0 # skipped 0
真正值得复用的不是某个正则,而是三层边界:先约定字段含义,再把逐行读取和单行判断分开,最后把数据不合格与系统读取失败区分开。契约变更时先补测试,再改解析函数,错误行号和退出码就能持续作为可靠的排查入口。


