我正在玩弄所有花哨的node.js/mongodb/express平台,偶然发现了一个问题:
app.get('/tag/:tag', function(req, res){
var tag=req.params.tag;
console.log('got tag ' + tag + '.');
catalog.byTag(tag,function(err,cursor) {
if(err) {
console.dir(err);
res.end(err);
} else {
res.writeHead(200, { 'Content-Type': 'application/json'});
//this crashes
cursor.stream().pipe(res);
}
});
});
Run Code Online (Sandbox Code Playgroud)
正如您可能猜到的那样,对Mongodb catalog.byTag(tag, callback)进行find()查询并返回光标
这会导致错误:
TypeError: first argument must be a string or Buffer
Run Code Online (Sandbox Code Playgroud)
根据mongodb驱动程序doc,我试图将此转换器传递给stream():
function(obj) {return JSON.stringify(obj);}
Run Code Online (Sandbox Code Playgroud)
但这没有用.
任何人都可以告诉我如何正确地将某些内容传递给响应吗?
或者是使用"数据"和"结束"事件手动泵送数据的样板的唯一解决方案?
这是自定义可读流的实现的简短示例。该类称为MyStream。流从目录中获取文件/文件夹名称,并将值推送到数据事件。
为了比较,我实现了(在此示例中)两种不同的方式/功能。一个是同步的,另一个是异步的。构造函数的第二个参数让您决定使用哪种方式(对于异步,为true,对于同步为false。
readcounter计数调用方法_read的次数。仅提供反馈。
var Readable = require('stream').Readable;
var util = require('util');
var fs = require('fs');
util.inherits(MyStream, Readable);
function MyStream(dirpath, async, opt) {
Readable.call(this, opt);
this.async = async;
this.dirpath = dirpath;
this.counter = 0;
this.readcounter = 0;
}
MyStream.prototype._read = function() {
this.readcounter++;
if (this.async === true){
console.log("Readcounter: " + this.readcounter);
that = this;
fs.readdir(this.dirpath,function(err, files){
that.counter ++;
console.log("Counter: " + that.counter);
for (var i = 0; i < files.length; i++){
that.push(files[i]);
}
that.push(null);
});
} else {
console.log("Readcounter: " + …Run Code Online (Sandbox Code Playgroud)