如果800k的logging需要50秒,队列中的所有http pending请求将会阻塞50秒,因为服务器变得理想

如果800k的logging需要50秒,队列中的所有http pending请求将会阻塞50秒,因为服务器变得理想。

var http = require("http"); var url = require("url"); var MongoClient = require('mongodb').MongoClient http.createServer(function(request, response) { if (url.parse(request.url).pathname == '/search'){ var collection = db.collection('documents'); // suppose it takes 800k record in 40 secs all request would be block until response end collection.find({}).toArray(function(err, docs) { console.log("Found the following records"); console.dir(docs); response.writeHead(200, {"Content-Type": "text/plain"}); response.write(JSON.stringify(docs)); response.end(); }); } else { response.writeHead(200, {"Content-Type": "text/plain"}); response.write(0 + ''); response.end(); } }).listen(8888); 

MongoDB的本地nodejs驱动程序支持stream式传输 。 它提供了一个可读的stream,你可以pipe道响应。 或者,写一个转换stream来即时转换文档。

  collection.find({}).stream().pipe(myTransform).pipe(response); 

这种方法不会等待加载内存中的所有文档( toArray() ),然后双重加载它( JSON.stringify() )。 它将继续从mongdb转发数据到响应,并有一些缓冲。