Node.js内置模块readline在关闭后继续读取行

编程入门 行业动态 更新时间:2024-10-18 06:02:22

Node.js内置<a href=https://www.elefans.com/category/jswz/34/1771428.html style=模块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在关闭后继续读取行

本文发布于:2024-05-07 02:09:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754099.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模块   Node   js   readline

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!