Last active
December 16, 2015 05:19
-
-
Save hylom/5383731 to your computer and use it in GitHub Desktop.
Sample code: Load binary data from MongoDB and save to file with Node.js
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 fs = require('fs'); | |
var path = require('path'); | |
var mongodb = require('mongodb'); | |
var BSON = mongodb.BSON; | |
var DB_HOST = 'localhost'; | |
var DB_PORT = 27017 | |
var DB_OPTION = {}; | |
var DB_NAME = 'test01'; | |
// 以前は「safe: true」などと指定していたが、最新版では | |
// オプションの「w」プロパティで書き込み時の通知処理を指定する。 | |
// 後方互換性の維持のため、「safe: true」といった指定もまだ許可されている | |
var CONN_OPTION = {w:1}; | |
// メイン処理を実行する関数 | |
function main() { | |
if (process.argv.length < 3) { | |
console.log('usage: %s <filename>', process.argv[1]); | |
process.exit(-1); | |
} | |
var filename = process.argv[2]; | |
loadFromDB(filename, function(err,data) { | |
fs.writeFile(filename, data, function (err) { | |
if (err) { | |
throw err; | |
} | |
console.log('load succeeded.'); | |
}); | |
}); | |
} | |
// データをDBから取り出す | |
function loadFromDB(filename, callback) { | |
var server = new mongodb.Server(DB_HOST, DB_PORT, DB_OPTION); | |
var connector = new mongodb.Db(DB_NAME, server, CONN_OPTION); | |
connector.open(function (err, db) { | |
db.collection('images', function(err, collection) { | |
bson = { | |
'filename': filename, | |
}; | |
collection.find(bson, function(err, cursor) { | |
if (err) { | |
throw err; | |
} | |
// クエリ結果から最初の1件のみを取り出す | |
cursor.limit(1).each(function(err, doc) { | |
if (err) { | |
throw err; | |
} | |
// 読み出しが終了したらデータベースを閉じる | |
if (doc === null) { | |
db.close(); | |
return; | |
} | |
// バイナリの処理については | |
// http://mongodb.github.io/node-mongodb-native/api-bson-generated/binary.html | |
// を参照 | |
// 指定したサイズ分データを読み出す | |
var len = doc.data.length(); | |
callback(err, doc.data.read(0, len)); | |
}); | |
}); | |
}); | |
}); | |
} | |
// 直接このモジュールがnodeコマンドで実行されているならmain関数を実行する | |
if (require.main == module) { | |
main(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment