【问题标题】:How can I parse a large delimited text file in node如何解析节点中的大型分隔文本文件
【发布时间】:2013-07-02 18:29:36
【问题描述】:

我正在使用 Node 来处理来自应用程序的日志文件,由于流量很大,这些文件每天的大小可能是千兆字节左右。

文件每天晚上都被抓取,我需要读取文件而无需将它们解压缩到磁盘。

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

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

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

【问题讨论】:

  • 您是否考虑过编写本机扩展并使用 C++ 库?如果您的文件那么大,这可能是最好的选择...
  • 不知道 C++ tbh。目前我可以通过解压缩文件然后使用截止日期来做到这一点,但是当我将其滚动到生产环境中时,权限被锁定,所以我无法更改日志文件夹的内容,只能从中读取。
  • 尝试用 sudo 执行你的节点进程?
  • 要逐行解析文件,您可以在此处查看stackoverflow.com/a/16013228/568109。不过,您必须传递解压缩的流。
  • 以 sudo 运行服务并不是一个很好的安全实践

标签: node.js logging stream gzip pipe


【解决方案1】:

你应该看看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.
})

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多