模块readline在关闭后继续读取行"/>
Node.js内置模块readline在关闭后继续读取行
我有以下代码:
const fs = require("fs");
const {createInterface} = require("readline");
const {join} = require("path");
const {once} = require("events");
async function readMeta (path) {
const meta = {};
const rs = fs.createReadStream(path);
const lineReader = createInterface({input: rs});
let linesRead = 0;
lineReader.on("line", line => {
switch (linesRead) {
case 0:
meta.name = line;
break;
case 1:
meta.tags = line.split(" ");
break;
case 2:
meta.type = line;
break;
case 3:
meta.id = +line;
}
if (++linesRead === 4) {
lineReader.close();
}
});
await once(lineReader, "close");
rs.close();
return meta;
}
似乎正在运行,但是在触发line
事件时记录行显示了其他情况。调用lineReader.close()
后,仍会引发该事件,从而导致读取整个文件。我不知道是什么原因造成的。我发现了一些显然可以完成工作的模块,但是我想尽可能降低依赖关系。
我建议不要将处理和切换计数器推入阵列,并在阵列大小为4后防止进一步压入。
然后调用close,然后将数组解构为必要的属性并返回包含它们的对象。
const fs = require("fs");
const {createInterface} = require("readline");
const {join} = require("path");
const {once} = require("events");
async function readMeta (path) {
const meta = {};
const rs = fs.createReadStream(path);
const lineReader = createInterface({input: rs});
const linesRead = [];
lineReader.on("line", line => {
if (linesRead.length === 4) {
lineReader.close();
rs.close();
return;
}
linesRead.push(line.trim());
});
await once(lineReader, "close");
delete rs;
delete lineReader;
const [name, tags, type, id] = linesRead;
return {
id,
name,
type,
tags: tags.split(' '),
};
}
更多推荐
Node.js内置模块readline在关闭后继续读取行
发布评论