node.js - 在 Meteor 中,如何从集合查找游标中获取 Node 读取流?

标签 node.js mongodb stream meteor

在Meteor中,在服务器端,我想在Collection上使用.find()函数,然后从返回的curser中获取Node ReadStream接口(interface)。我已经尝试在curser上使用.stream(),如mongoDB文档Seen Here中所述。 。但是我收到错误“Object [object Object] has no method 'stream'”因此看起来 Meteor 集合没有此选项。有没有办法从 Meteor Collection 的诅咒器中获取流?

我正在尝试将一些数据导出到 CSV,并且希望将数据直接从集合流传输到 CSV 解析器,然后传输到返回给用户的响应中。我能够从我们正在使用的 Router 包中获取响应流,除了从集合中获取流之外,它一切正常。从查找中获取数组并手动将其插入流中会违背流的目的,因为它将把所有内容都放入内存中。我想我的另一个选择是在集合上使用 foreach 并将行逐一插入流中,但是当我可以通过解析器直接通过管道传输流并对其进行转换时,这看起来很脏。

这是我想要做的一些示例代码:

response.writeHead(200,{'content-type':'text/csv'});

// Set up a future
var fut = new Future();
var users = Users.find({}).stream();
CSV().from(users)
.to(response)
.on('end', function(count){
    log.verbose('finished csv export');
    response.end();
    fut.ret();
});
return fut.wait();

最佳答案

您是否尝试过创建自定义函数并通过管道连接到它?

不过,只有当 Users.find() 支持 .pipe() 时,这才有效(同样,只有当 Users.find 从 Node.js Streamble 对象继承时)。

有点像

var stream = require('stream')
var util = require('util')

streamreader = function (){
  stream.Writable.call(this)
  this.end = function() {
     console.log(this.data) //this.data contains raw data in a string so do what you need to to make it usable, i.e, do a split on ',' or something or whatever it is you need to make it usable
     db.close()
  })
}

util.inherits(streamreader,stream.Writeable)

stream.prototype._write = function (chunk, encoding, callback) {
  this.data = this.data + chunk.toString('utf8')
  callback()
}


Users.find({}).pipe(new streamReader())

关于node.js - 在 Meteor 中,如何从集合查找游标中获取 Node 读取流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17180699/

相关文章:

java - 为什么java没有StringBufferOutputStream

c# - 流式传输为 UTF8 字符串,不带 byte[]

mysql - 如何在 node.js 中使用 token(post) Mysql?

node.js - 自动缩小所有 node_modules

django - Django 中的 Mongodb 与 PostgreSQL

java - 在 Spring Boot MVC 应用程序中在 JPA 和 Mongo 之间切换

c# - 如何将部分预缓存的MemoryStream与FileStream结合起来?

json - 无法读取 MongoDB Id 格式 |显示为缓冲区数组

javascript - createWriteStream 后 gulp-open 不起作用

用于计算按其他字段分组的唯一字段数的 Mongodb 查询