node.js - 如何解析 Node 中的大型分隔文本文件

标签 node.js logging stream gzip pipe

我正在使用 Node 处理来自应用程序的日志文件,由于流量的原因,这些文件每天的大小可能达到 GB 左右。

这些文件每天晚上都紧握着,我需要读取这些文件,而不必将它们解压缩到磁盘。

据我了解,我可以使用 zlib 将文件解压缩为某种形式的流,但我不知道如何获取数据,也不知道如何一次轻松处理一行(尽管我知道将涉及某种搜索\n 的 while 循环。

到目前为止我发现的最接近的答案是演示如何将流传输到 sax 解析器,但是整个 Node 管道/流有点令人困惑

fs.createReadStream('large.xml.gz').pipe(zlib.createUnzip()).pipe(saxStream);

最佳答案

您应该看看sax 。 它是由isaacs 开发的!

我还没有测试过这段代码,但我会首先沿着这些思路写一些东西。

var Promise = Promise || require('es6-promise').Promise
, thr = require('through2')
, createReadStream = require('fs').createReadStream
, createUnzip = require('zlib').createUnzip
, createParser = require('sax').createStream
;

function processXml (filename) {
  return new Promise(function(resolve, reject){
    var unzip = createUnzip()
    , xmlParser = createParser()
    ;

    xmlParser.on('opentag', function(node){
      // do stuff with the node
    })
    xmlParser.on('attribute', function(node){
      // do more stuff with attr 
    })

    // instead of rejecting, you may handle the error instead.
    xmlParser.on('error', reject) 
    xmlParser.on('end', resolve)

    createReadStream(filename)
    .pipe(unzip)
    .pipe(xmlParser)
    .pipe(thr(function(chunk, enc, next){
      // as soon xmlParser is done with a node, it passes down stream.
      // change the chunk if you wish
      next(null, newerChunk)
    }))

    rl = readline.createInterface({
      input: unzip
    , ouput: xmlParser
    })
  })
}

processXml('large.xml.gz').then(function(){
  console.log('done')
})
.catch(function(err){
  // handle error.
})

希望有帮助

关于node.js - 如何解析 Node 中的大型分隔文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17433148/

相关文章:

logging - Service Fabric 参与者和服务的关联 token

c# - Stream.Seek(0, SeekOrigin.Begin) 或 Position = 0

javascript - 我总是收到 JSON 循环结构错误和未处理的 promise 拒绝警告。我该如何摆脱它?

sql-server - Node mssql 连接错误 : Login failed for user ' '

node.js - Node.js 中的日志轮换?

c# - Quartz.net 和 Common.Logging - 使用 Log4Net

logging - 如何在 Camel 的 onException 子句中设置记录器(日志类别/日志名称)?

node.js - 最简单的 nodejs 回显服务器

php - 多表连接时仅从一张表获取数据

javascript - 使用 AES 时,Crypto-js 每次运行时都会返回不同的值