Skip to content

Instantly share code, notes, and snippets.

@Starefossen
Last active June 22, 2020 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Starefossen/8003095 to your computer and use it in GitHub Desktop.
Save Starefossen/8003095 to your computer and use it in GitHub Desktop.
Stream MongoDB documents from Node.JS server
"use strict"
http = require 'http'
MongoClient = require('mongodb').MongoClient
stringify = require('JSONStream').stringify
db = null
server = http.createServer (req, res) ->
cursor = db.collection('turer').find()
stream = cursor.stream()
res.writeHead 200, 'Content-Type': 'application/json; charset=utf-8'
op = '{"documents":['
cl = '],"count":0,"total":0}'
stream.pipe(stringify(op, ',', cl)).pipe(res)
MongoClient.connect 'mongodb://localhost:27017/test', (err, database) ->
db = database
server.listen 8080, -> console.log 'Server is listening on port 4000...'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment