Node.js readline missing last line of file?

2019-02-13 13:37发布

问题:

I'm trying to read a text file asynchronously and line-by-line under Node.js. I have the following CoffeeScript code:

readline  = require 'readline'
fs        = require 'fs'

#--------------------------------------------------------------------
lines_of = ( route, handler ) ->
  #..................................................................
  stream = readline.createInterface
    input:    fs.createReadStream route
    output:   process.stdout
    terminal: false
  #..................................................................
  stream.on 'close', ->
    handler null, null
  #..................................................................
  stream.on 'error', ( error ) ->
    handler error
  #..................................................................
  stream.on 'line', ( line ) ->
    handler null, line

It works fine except the very last line of files is never reported unless it is terminated by a newline. is there any way to remedy this (except, of course, adding the newline manually)?

回答1:

You should use the fs module for this, and split the file contents on \n chars to determine where lines end.