Node.js JSON 转 CSV:固定列、严格校验与防覆盖导出实践
把对象的值用逗号连接,并不等于完成了 CSV 导出。备注中的一个逗号就能让列错位,换行会制造“多出来的一行”,双引号又需要自己的转义规则。更隐蔽的问题是:缺字段被默默补空、字符串数字混入统计列,或者第二次运行覆盖了上次的结果。本文用 Node.js 标准库实现一个小型、可验证的 JSON 转 CSV 命令行工具,不安装依赖,也不把它包装成通用转换框架。

一、先固定数据契约,而不是猜测字段
示例处理库存清单,输入是无 BOM 的 UTF-8 JSON 普通文件,最多 1 MiB、1000 条记录。每条记录只能包含 id、name、count、active、note 五个字段;列序固定,行序沿用输入,不自动排序或去重。空数组输出表头,便于下游使用同一套导入逻辑。
id 是非空字符串,以保留“0007”这样的业务编号;name、note 可以为空字符串。count 必须是非负安全整数,active 只能是真正的布尔值。缺字段、未知字段、null、嵌套对象以及“2”“false”这样的错误类型直接报错,不做隐式转换。文本保留中文、emoji、空格、单双引号和 CR/LF,但拒绝孤立代理项及制表符等指定控制字符。
为什么不能用“值或空字符串”统一兜底?零库存和未启用状态都是有效业务值,不能与缺失混为一谈。类似地,字段多了也不能直接忽略:它可能意味着上游升级了协议,或者把 note 拼成了 notes。让任务明确失败,比生成一个看似成功却少了信息的文件更容易排查。逐条记录阶段的校验错误带记录序号,定位后应修正输入,而不是跳过坏行继续导出。
二、CSV 转义只负责字段边界
本实现采用 RFC 4180 的常见引号规则:含逗号、双引号或换行的字段加双引号,字段内部的双引号写成两个。记录之间使用 CRLF,末尾也保留 CRLF;字段内部原有换行不改写。输出使用 UTF-8 且不加 BOM。这是采用该转义约定的 Unicode 实用格式,不声称所有 CSV 软件行为完全一致。
另一个容易遗漏的边界是数字精度。只在 JSON.parse 之后检查整数还不够,某些小数可能已经舍入成整数。因此代码读取 reviver 的 context.source,要求数值原文只使用无符号整数字面量:2 可以,2.0、2e0、-0 都拒绝。随后再检查安全整数范围。这是有意收紧的业务契约,不是 JSON 语法的一般限制。
三、完整导出脚本
将下面内容保存为 export.cjs,使用 Node.js 24 运行。脚本先有界读取并严格解码,再完成全部校验和序列化,最后才创建输出文件。任何输入错误都不会先留下一个只有表头的 CSV。
"use strict";
const fs = require("node:fs");
const { TextDecoder } = require("node:util");
const COLUMNS = Object.freeze(["id", "name", "count", "active", "note"]);
const MAX_BYTES = 1024 * 1024;
const MAX_ROWS = 1000;
function readSmallJson(path) {
const fd = fs.openSync(path, "r");
let bytes;
try {
if (!fs.fstatSync(fd).isFile()) throw new Error("input must be a regular file");
const buffer = Buffer.alloc(MAX_BYTES + 1);
let size = 0;
while (size < buffer.length) {
const n = fs.readSync(fd, buffer, size, buffer.length - size, null);
if (n === 0) break;
size += n;
}
if (size > MAX_BYTES) throw new Error("input exceeds 1 MiB");
bytes = buffer.subarray(0, size);
} finally {
fs.closeSync(fd);
}
const text = new TextDecoder("utf-8", {
fatal: true, ignoreBOM: true
}).decode(bytes);
return JSON.parse(text, (key, value, context) => {
if (typeof value === "number" &&
(!/^(0|[1-9]\d*)$/.test(context.source) ||
!Number.isSafeInteger(value))) {
throw new Error("numbers must be unsigned safe integer literals");
}
return value;
});
}
function csvCell(value) {
const text = String(value);
return /[",\r\n]/.test(text)
? '"' + text.replaceAll('"', '""') + '"'
: text;
}
function toCsv(records) {
if (!Array.isArray(records) || records.length > MAX_ROWS) {
throw new Error("input must be an array of at most 1000 records");
}
const lines = [COLUMNS.join(",")];
for (let i = 0; i < records.length; i++) {
const row = records[i];
const fail = (message) => {
throw new Error(`record ${i + 1}: ${message}`);
};
if (row === null || typeof row !== "object" || Array.isArray(row) ||
Object.getPrototypeOf(row) !== Object.prototype) {
fail("expected a plain JSON object");
}
if (Reflect.ownKeys(row).length !== COLUMNS.length ||
!COLUMNS.every((key) => Object.hasOwn(row, key))) {
fail("expected exactly id, name, count, active, note");
}
for (const key of ["id", "name", "note"]) {
if (typeof row[key] !== "string" || !row[key].isWellFormed() ||
/[\u0000-\u0009\u000B\u000C\u000E-\u001F\u007F]/.test(row[key])) {
fail(`${key} must be a well-formed string without forbidden controls`);
}
}
if (row.id.length === 0) fail("id must not be empty");
if (!Number.isSafeInteger(row.count) || row.count < 0 ||
Object.is(row.count, -0)) {
fail("count must be a non-negative safe integer");
}
if (typeof row.active !== "boolean") fail("active must be a boolean");
lines.push(COLUMNS.map((key) => csvCell(row[key])).join(","));
}
return lines.join("\r\n") + "\r\n";
}
function main(args) {
if (args.length !== 2) {
throw new Error("usage: node export.cjs input.json output.csv");
}
const csv = toCsv(readSmallJson(args[0]));
fs.writeFileSync(args[1], csv, { encoding: "utf8", flag: "wx", mode: 0o600 });
}
if (require.main === module) {
try {
main(process.argv.slice(2));
} catch (error) {
console.error(error.code === "EEXIST"
? "output exists; refusing to overwrite"
: error.message);
process.exitCode = 1;
}
}
module.exports = { toCsv, readSmallJson, main };四、用包含特殊字符的输入试跑
保存下面内容为 input.json。JSON 中的反斜杠转义在解析后会变成真实换行和双引号,CSV 导出必须处理的是解析后的字符,而不是原始 JSON 的视觉排版。
[
{
"id": "0007",
"name": "林舟",
"count": 2,
"active": false,
"note": "南区,北区\n他说\"收到\"🙂"
}
]在同一目录执行以下命令。成功时退出码为 0;出错时退出码为 1,原因写到标准错误。为了避免复制时混淆,命令中的两个文件名分别是输入路径和新输出路径。
node export.cjs input.json output.csv
这里没有“先判断存在,再写入”的窗口:Node.js 的 wx 标志要求独占创建,输出已存在就失败,不覆盖旧内容。输入输出同名也会失败。这个保证依赖文件系统对独占创建的支持,不能直接推及所有网络文件系统;磁盘写入中途失败仍可能留下新建的残缺文件,它也不是断电安全的事务写入。
日常批处理可以给输出名加入批次号,确认成功后再交给下游;不要把“文件存在”当成“本次导出完成”。调用方应检查退出码,并区分输入校验失败和磁盘写入失败。本文使用同步接口是为了让短命令行脚本清晰,不能原样搬到高并发服务的请求处理路径。
五、不要用 split 换行验证 CSV
测试应当验证“读回后值相同”,而不只是看文件能否打开。下面的测试解析器独立实现字符状态机,没有调用导出器的转义函数,也没有按行拆分;这样才能检验引号内换行,并避免同一段错误逻辑自证正确。保存为 export.test.cjs。
展开完整测试:80 项,包含独立解析器与 CLI
"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { spawnSync } = require("node:child_process");
const { toCsv } = require("./export.cjs");
const cli = path.join(__dirname, "export.cjs");
const header = ["id", "name", "count", "active", "note"];
const record = (patch = {}) => ({
id: "0007", name: "林舟", count: 2, active: true, note: "", ...patch
});
// Independent state-machine reader: no exporter helpers or split-by-line logic.
function parseCsv(text) {
const rows = [];
let row = [], field = "", state = "start";
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (state === "quoted") {
if (c !== '"') field += c;
else if (text[i + 1] === '"') { field += '"'; i++; }
else state = "closed";
continue;
}
if (state === "start" && c === '"') { state = "quoted"; continue; }
if (c === ",") {
row.push(field); field = ""; state = "start"; continue;
}
if (c === "\r" && text[i + 1] === "\n") {
row.push(field); rows.push(row);
row = []; field = ""; state = "start"; i++; continue;
}
if (state === "closed" || c === '"' || c === "\r" || c === "\n") {
throw new Error("invalid CSV boundary");
}
field += c;
state = "bare";
}
if (state === "quoted") throw new Error("unclosed CSV quote");
if (row.length || field.length || state !== "start") {
row.push(field); rows.push(row);
}
return rows;
}
function fixture(t, input = JSON.stringify([record()])) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "json-csv-"));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const source = path.join(dir, "input.json");
const output = path.join(dir, "output.csv");
fs.writeFileSync(source, input);
const run = (args = [source, output]) =>
spawnSync(process.execPath, [cli, ...args], { encoding: "utf8" });
return { dir, source, output, run };
}
test("empty array retains a header and final CRLF", () => {
assert.equal(toCsv([]), "id,name,count,active,note\r\n");
});
test("plain record has exact deterministic bytes", () => {
assert.equal(toCsv([record()]), "id,name,count,active,note\r\n0007,林舟,2,true,\r\n");
});
test("property insertion order does not change columns", () => {
assert.equal(toCsv([{ note: "", active: true, count: 2, name: "林舟", id: "0007" }]),
toCsv([record()]));
});
test("record order is preserved", () => {
assert.deepEqual(parseCsv(toCsv([record({ id: "z" }), record({ id: "a" })]))
.slice(1).map((r) => r[0]), ["z", "a"]);
});
const strings = [
["comma", "南区,北区"], ["double quote", '他说"好"'],
["LF", "一\n二"], ["CR", "一\r二"], ["CRLF", "一\r\n二"],
["emoji and multilingual text", "你好🙂 café العربية"],
["combining marks", "e\u0301"], ["spaces", " 两端 "],
["empty string", ""], ["only quotes", '""'],
["mixed separators", 'a,\r\n"b",c'],
["formula-looking text", "=1+1"], ["plus-looking text", "+SUM(A1)"],
["at-looking text", "@something"], ["minus-looking text", "-2+3"]
];
for (const [label, value] of strings) {
test(`round trip: ${label}`, () => {
const rows = parseCsv(toCsv([record({ note: value })]));
assert.deepEqual(rows, [header, ["0007", "林舟", "2", "true", value]]);
});
}
test("false and zero are not treated as missing", () => {
assert.deepEqual(parseCsv(toCsv([record({ count: 0, active: false })]))[1],
["0007", "林舟", "0", "false", ""]);
});
test("maximum safe count is accepted", () => {
assert.equal(parseCsv(toCsv([record({ count: Number.MAX_SAFE_INTEGER })]))[1][2],
"9007199254740991");
});
test("1000 rows are accepted", () => {
assert.equal(parseCsv(toCsv(Array.from({ length: 1000 }, () => record()))).length, 1001);
});
const invalid = [
["null root", null], ["object root", {}], ["string root", "[]"],
["null record", [null]], ["array record", [[]]], ["number record", [3]],
["missing field", [{ id: "a", name: "", count: 1, active: true }]],
["unknown field", [record({ extra: 1 })]],
["unknown replacing a required field",
[{ id: "a", name: "", count: 1, active: true, other: "" }]],
["null string", [record({ name: null })]], ["numeric string field", [record({ id: 7 })]],
["empty id", [record({ id: "" })]], ["nested object", [record({ note: {} })]],
["string count", [record({ count: "2" })]], ["boolean count", [record({ count: true })]],
["fractional count", [record({ count: 1.5 })]], ["negative count", [record({ count: -1 })]],
["negative zero count", [record({ count: -0 })]],
["unsafe count", [record({ count: Number.MAX_SAFE_INTEGER + 1 })]],
["NaN count", [record({ count: NaN })]], ["infinite count", [record({ count: Infinity })]],
["string boolean", [record({ active: "false" })]],
["numeric boolean", [record({ active: 0 })]], ["null boolean", [record({ active: null })]],
["undefined field", [record({ note: undefined })]],
["unpaired high surrogate", [record({ note: "\uD800" })]],
["unpaired low surrogate", [record({ note: "\uDC00" })]],
["tab control", [record({ note: "\t" })]], ["NUL control", [record({ note: "\0" })]],
["DEL control", [record({ note: "\u007F" })]],
["more than 1000 records", Array.from({ length: 1001 }, () => record())],
["non-JSON prototype", [Object.assign(Object.create({ inherited: 1 }), record())]],
["symbol key", [record({ [Symbol("extra")]: 1 })]],
["sparse array", new Array(1)]
];
for (const [label, value] of invalid) {
test(`reject: ${label}`, () => assert.throws(() => toCsv(value)));
}
test("independent parser handles reference quoted fields", () => {
assert.deepEqual(parseCsv('a,"b""c","d\r\ne"\r\n'), [["a", 'b"c', "d\r\ne"]]);
});
test("independent parser rejects malformed quotes", () => {
for (const input of ['"a', 'a"b\r\n', '"a"x\r\n', "a\n"]) {
assert.throws(() => parseCsv(input));
}
});
test("CLI creates UTF-8 CSV and independent parser restores strings", (t) => {
const input = record({ note: '换行\n与"引号",🙂', active: false });
const f = fixture(t, JSON.stringify([input]));
const result = f.run();
assert.equal(result.status, 0, result.stderr);
const bytes = fs.readFileSync(f.output);
assert.notEqual(bytes.subarray(0, 3).toString("hex"), "efbbbf");
assert.deepEqual(parseCsv(bytes.toString("utf8")),
[header, ["0007", "林舟", "2", "false", input.note]]);
});
test("CLI refuses overwrite and keeps original bytes", (t) => {
const f = fixture(t);
fs.writeFileSync(f.output, "KEEP THIS");
const result = f.run();
assert.equal(result.status, 1);
assert.match(result.stderr, /refusing to overwrite/);
assert.equal(fs.readFileSync(f.output, "utf8"), "KEEP THIS");
});
test("CLI refuses using input as output without changing it", (t) => {
const f = fixture(t);
const before = fs.readFileSync(f.source);
assert.equal(f.run([f.source, f.source]).status, 1);
assert.deepEqual(fs.readFileSync(f.source), before);
});
test("CLI refuses existing symlink without changing target", (t) => {
const f = fixture(t);
fs.symlinkSync(f.source, f.output);
const before = fs.readFileSync(f.source);
assert.equal(f.run().status, 1);
assert.deepEqual(fs.readFileSync(f.source), before);
assert.ok(fs.lstatSync(f.output).isSymbolicLink());
});
test("CLI refuses dangling symlink without creating target", (t) => {
const f = fixture(t);
const target = path.join(f.dir, "absent.csv");
fs.symlinkSync(target, f.output);
assert.equal(f.run().status, 1);
assert.equal(fs.existsSync(target), false);
});
for (const [label, input] of [
["malformed JSON", "{"],
["trailing data", "[] trailing"],
["UTF-8 BOM", Buffer.concat([Buffer.from([0xEF, 0xBB, 0xBF]), Buffer.from("[]")])],
["invalid UTF-8", Buffer.from([0x5B, 0x22, 0xC3, 0x28, 0x22, 0x5D])],
["invalid schema", JSON.stringify([record({ active: "true" })])],
["oversize input", " ".repeat(1024 * 1024 + 1)],
["decimal literal", JSON.stringify([record()]).replace('"count":2', '"count":2.0')],
["exponent literal", JSON.stringify([record()]).replace('"count":2', '"count":2e0')],
["precision-rounded literal", JSON.stringify([record()]).replace('"count":2', '"count":1.0000000000000001')],
["negative zero literal", JSON.stringify([record()]).replace('"count":2', '"count":-0')],
["overflow literal", JSON.stringify([record()]).replace('"count":2', '"count":1e400')],
["unsafe integer literal", JSON.stringify([record()]).replace('"count":2', '"count":9007199254740993')]
]) {
test(`CLI rejects ${label} before creating output`, (t) => {
const f = fixture(t, input);
assert.equal(f.run().status, 1);
assert.equal(fs.existsSync(f.output), false);
});
}
test("CLI accepts exactly 1 MiB of valid JSON", (t) => {
const f = fixture(t, "[]".padEnd(1024 * 1024, " "));
assert.equal(f.run().status, 0);
assert.equal(fs.readFileSync(f.output, "utf8"), "id,name,count,active,note\r\n");
});
test("CLI wrong argument count is a nonzero usage error", (t) => {
const f = fixture(t);
const result = f.run([]);
assert.equal(result.status, 1);
assert.match(result.stderr, /usage:/);
});
test("CLI missing source fails without output", (t) => {
const f = fixture(t);
assert.equal(f.run([path.join(f.dir, "missing.json"), f.output]).status, 1);
assert.equal(fs.existsSync(f.output), false);
});
test("CLI rejects a directory source", (t) => {
const f = fixture(t);
assert.equal(f.run([f.dir, f.output]).status, 1);
assert.equal(fs.existsSync(f.output), false);
});
test("CLI reports missing output parent", (t) => {
const f = fixture(t);
const result = f.run([f.source, path.join(f.dir, "missing", "output.csv")]);
assert.equal(result.status, 1);
assert.match(result.stderr, /ENOENT/);
});执行测试命令。本次在 Node.js v24.19.0、Linux 环境实际通过 80 项测试,失败和跳过均为 0。覆盖固定列序、Unicode 与多种换行往返、错误字段和类型、异常数字字面量、输入大小边界、真实 CLI、已有文件及符号链接保护。符号链接测试按本次 Linux 环境验证,不等于已经完成其他操作系统的兼容性认证。
node --test export.test.cjs
六、CSV 正确,不等于电子表格安全
如果备注以等号、加号等字符开头,某些电子表格软件可能把它当公式。给字段加双引号并不能消除这个风险。本文保留原文,包括“=1+1”,测试也明确验证了这一点;它适合约定好格式的程序间交换,不应把来自不可信用户的输出直接当作安全表格分发。
OWASP 的 CSV 注入说明也区分了字段转义与公式执行。需要给人用表格查看时,应针对具体软件另定导入或导出策略,并测试保存、重开后的行为。直接加前缀会改变数据,不能悄悄混进“无损导出”;也不要把某一种规避办法宣传成跨软件万能防护。
七、把边界写进使用说明
本例不解析任意嵌套结构,不做金额精度计算,不处理大文件流式转换。JSON.parse 对重复对象键采用后值覆盖,脚本没有增加重复键检测;若输入协议要求拒绝重复键,应换用能报告该错误的解析方案。CSV 本身不携带字段类型,下游仍需按契约恢复 count 和 active,业务编号也应按文本导入,避免丢掉前导零。
这个工具真正值得复用的不是几行 replace,而是顺序:先写清数据契约,再验证边界,最后独占写文件。需求变大时可以替换实现,但不要先删掉这些约束和测试。

