Created
May 26, 2016 00:22
-
-
Save kevinadi/b3fa3f4c95ace9ce7a68acfccda5304f to your computer and use it in GitHub Desktop.
Save binary file in MongoDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoBinary = { | |
save : function(url, collection, filename) { | |
var fs = require('fs') | |
var Binary = require('mongodb').Binary | |
var MongoClient = require('mongodb').MongoClient | |
var assert = require('assert') | |
var doc = { | |
name: filename, | |
data: new Binary(fs.readFileSync(filename)) | |
} | |
MongoClient.connect(url, function(err,db) { | |
assert.equal(null,err,err) | |
db.collection(collection).insert(doc, function(err,res) { | |
assert.equal(null,err,err) | |
console.log(res) | |
}) | |
}) | |
}, | |
write : function(url, collection, filename, outname) { | |
var outname = outname || filename | |
var fs = require('fs') | |
var Binary = require('mongodb').Binary | |
var MongoClient = require('mongodb').MongoClient | |
var assert = require('assert') | |
var doc = { | |
name: filename | |
} | |
MongoClient.connect(url, function(err,db) { | |
assert.equal(null,err,err) | |
db.collection(collection).find(doc).next(function(err,res) { | |
assert.equal(null,err,err) | |
fs.writeFile(outname, res.data.buffer, function(err) { | |
assert.equal(null,err,err) | |
console.log('File ' + outname + ' saved.') | |
}) | |
}) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment