28

Node.js は初めてです。Node.js と Mongoose を使用して、画像などのバイナリ データを格納および取得するために GridFS を使用する方法の例を誰か教えてもらえますか? GridFS に直接アクセスする必要がありますか?

4

4 に答える 4

27

ここで最高評価の回答に満足できなかったので、新しい回答を提供します .npm経由でインストールできるノードモジュール「gridfs-stream」 (素晴らしいドキュメントがあります!)を使用することになりました。これをマングースと組み合わせると、次のようになります。

var fs = require('fs');
var mongoose = require("mongoose");
var Grid = require('gridfs-stream');
var GridFS = Grid(mongoose.connection.db, mongoose.mongo);

function putFile(path, name, callback) {
    var writestream = GridFS.createWriteStream({
        filename: name
    });
    writestream.on('close', function (file) {
      callback(null, file);
    });
    fs.createReadStream(path).pipe(writestream);
}

path は、ローカル システム上のファイルのパスであることに注意してください。

私のファイルの読み取り機能に関しては、私の場合、ファイルをブラウザにストリーミングするだけです(エクスプレスを使用):

try {
    var readstream = GridFS.createReadStream({_id: id});
    readstream.pipe(res);
} catch (err) {
    log.error(err);
    return next(errors.create(404, "File not found."));
}
于 2014-04-09T16:34:37.253 に答える
9

この質問を見ることをお勧めします: MongoDB GridFS Saving Files with Node.JS の問題

回答からコピーされた例(クレジットはchristkvに送られます):

// You can use an object id as well as filename now
var gs = new mongodb.GridStore(this.db, filename, "w", {
  "chunk_size": 1024*4,
  metadata: {
    hashpath:gridfs_name,
    hash:hash,
    name: name
  }
});

gs.open(function(err,store) {
  // Write data and automatically close on finished write
  gs.writeBuffer(data, true, function(err,chunk) {
    // Each file has an md5 in the file structure
    cb(err,hash,chunk);
  });
});
于 2011-11-15T12:29:43.810 に答える
3

writeBuffer は廃止されたようです。

/Users/kmandrup/private/repos/node-mongodb-native/HISTORY:
   82  * Fixed dereference method on Db class to correctly dereference Db reference objects. 
   83  * Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility.
   84: * Removed writeBuffer method from gridstore, write handles switching automatically now.
   85  * Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore.
于 2012-04-09T20:53:41.617 に答える