Node.js readline 缺少文件的最后一行? [英] Node.js readline missing last line of file?

查看:15
本文介绍了Node.js readline 缺少文件的最后一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Node.js 下异步逐行读取文本文件.我有以下 CoffeeScript 代码:

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

推荐答案

您应该为此使用 fs 模块,并将 字符上的文件内容拆分为确定行结束的位置.

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

这篇关于Node.js readline 缺少文件的最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆