Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js readline missing last line of file?

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)?

like image 654
flow Avatar asked Aug 26 '13 18:08

flow


1 Answers

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

like image 105
erikvold Avatar answered Sep 28 '22 06:09

erikvold