V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
youmoo
V2EX  ›  Node.js

Node.js 一行一行地读取文本文件

  •  1
     
  •   youmoo · May 27, 2020 · 5259 views
    This topic created in 2173 days ago, the information mentioned may be changed or developed.

    在 Node.js 中读取文本文件,我们经常使用的是:

    1. fs.readFile
    2. fs.createReadStream

    但这 2 个方法都没有对按行读取的支持,怎么办?

    Node.js 内置了一个 readline 模块,可以实现这个。

    更详细的情景说明,我写了 一篇文章

    5 replies    2020-05-31 13:50:33 +08:00
    gimp
        1
    gimp  
       May 27, 2020
    呃...
    MidLinn
        2
    MidLinn  
    PRO
       May 27, 2020
    额,不是可以 fs.open 然后 fs.read ?
    sunzongzheng
        3
    sunzongzheng  
       May 27, 2020
    LennieChoi
        4
    LennieChoi  
       May 27, 2020
    前阵子刚用到 readline,我分享下我碰到的问题。
    公司的环境是 node v10.15 的,发现这版本 readline.createInterface 创建出来的不是 async iterator 对象,无法对他 for await 遍历(v10.16 可以,就差 0.1 版本,哭)。领导还不让升级,因为是生产环境下要跑的脚本,不能随便升 node 版本。
    这里我的做法是用 stream.PassThrough 套一层,readline 读出来的数据写进 stream 里,然后 for await 这个 stream 对象。
    function readliner () {
    const output = new stream.PassThrough({ objectMode: true })
    const rl = readline.createInterface({
    input: fs.createReadStream('filepath')
    })

    rl.on('line', async (line) => {
    output.write(line)
    })
    rl.on('close', () => {
    output.push('end')
    });
    return output
    }

    注意:rl.on('close') 事件里写个 end 标记进去,以便再外层遍历的时候碰到 end 标记了可以 break 掉
    xcstream
        5
    xcstream  
       May 31, 2020
    一般什么功能 找找 npm 网站 99%可以解决
    https://www.npmjs.com/package/line-read
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4078 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 68ms · UTC 05:08 · PVG 13:08 · LAX 22:08 · JFK 01:08
    ♥ Do have faith in what you're doing.