NodeJS 从节点fs读取读取流,一次n行

b5lpy0ml  于 2023-01-04  发布在  Node.js
关注(0)|答案(1)|浏览(193)

我想保持fs读取流打开,并在需要手动读取时一次读取n行。我不想将on()事件处理程序与'data'挂钩,因为它会使流连续自动读取,直到结束。不知道手动触发读取下一组行需要多长时间。

6za6bjd0

6za6bjd01#

我做了一个简短的函数它应该能完成你想要的

const { createReadStream } = require('fs');
// wrapping everything in async function so await can be used
// not needed when global await is available
(async () => {
  // create readable stream
  const stream = createReadStream('lorem.txt', { encoding: 'utf-8' })

  // get readLine function instance
  const { readLine } = await createReader(stream)

  // read 100 lines, you can read as many as you want
  // don't have to read all at once
  for (let i = 0; i < 100; i += 1) {
    console.log(readLine())
  }

  // readLine factory
  async function createReader(stream) {
    // current bytes
    let bytes = ''

    // await for stream to load and be readable
    await new Promise(r => stream.once('readable', r))

    // return readLine function
    return {
      readLine() {
        let index
        // while there is no new line symbol in current bytes
        while ((index = bytes.indexOf('\n')) === -1) {
          // read some data from stream
          const data = stream.read()
          // if data is null it means that the file ended
          if (data === null) {
            // if no bytes left just return null
            if (!bytes) return null
            // if there are some bytes left return them and clear bytes
            const rest = bytes
            bytes = ''
            return rest
          }
          bytes += data
        }
        // get characters till new line
        const line = bytes.slice(0, index)
        // remove first line from current bytes
        bytes = bytes.slice(index + 1)
        // return the first line
        return line
      }
    }
  }
})()

相关问题