Getting node.js and gridfs to play nice is not easy. Of all the things I tried, I settled on this being as close as I could get with limited knowledge and what I understand the current supported functions will allow.
(below in coffee, use http://js2coffee.org/ to get to the js and vice versa)
util = require("util")
mongodb = require("mongodb")
GridStore = mongodb.GridStore
parse = (options) ->
opts = {}
opts = options[0] if options.length > 0
opts.metadata = {} unless opts.metadata
opts
db = new Db("local", new Server("127.0.0.1", 27017,
auto_reconnect: false
poolSize: 1
),
native_parser: false
)
db.open()
putFile = (path, name, options, fn) ->
options = parse(options)
options.metadata.filename = name
new GridStore(db, name, "w", options).open (err, file) ->
return fn(err) if err
file.writeFile path, (err, fn) ->
file.close()
opts = content_type: "plain/text"
myfileupload = putFile("myfile.txt", "known_hosts", opts)
db.close()
Strangely however, using apt-get install mongodb-10gen on Ubuntu 11.10, my file is not saved. And there are no error messages to help me understand why.
I am close to believing that everything I read about gridfs and nodejs is all just a cruel joke, and I am never going to see this work. Please help.
I suspect an async issue. You're calling db.close()
immediately after the call to putFile
, so db.close()
is running before the GridStore
's open
callback fires, right? Seems like it could be a problem. Try moving db.close()
into the same callback as file.close()
.