我一直在努力让网格(mongodb)在node中工作,要么我走错了路,要么网格系统并不是真的那么稳定。我尝试了大约三种不同的解决方案,现在决定尝试使用gridfs-stream (如果没有人知道更好的解决方案)。
我想我已经差不多把它弄好了。但它只是挂在读取的文件上(我想)
var mongoose = require("mongoose");
var fs = require("fs");
var mongo = require('mongodb');
var Grid = require('gridfs-stream');
mongoose.connect('mongodb://localhost:27017/BabySounds');
function loadFile(dataCollection, cuID, file){
console.log("Will create id " + cuID + " in the collection " + dataCollection + " and store " + file);
var gfs = new Grid(mongoose.connection.db, mongoose.mongo);
var writeStream = gfs.createWriteStream({
mode: 'w',
_id: cuID
});
fs.createReadStream(file).pipe(writeStream);
writeStream.on('close', function (filen) {
console.log('Written file ' + filen.name);
});
}
loadFile( 'fsSound', cuSoundID, srcSound); 但是,如果运行上面的代码,它只会创建文件,但(据我所知)永远不会到达close语句writeStream.on('close',
=======更新=======
更新了代码,添加了我能想到的尽可能多的测试。
var mongoose = require("mongoose");
var fs = require("fs");
var mongo = require('mongodb');
var Grid = require('gridfs-stream');
mongoose.connect('mongodb://localhost:27017/BabySounds');
var db = mongoose.connection;
function loadFile(dataCollection, cuID, file){
console.log("Will create id " + cuID + " in the collection " + dataCollection + " and store " + file);
var gfs = new Grid(mongoose.connection.db, mongoose.mongo);
db.on('error', function(err){
console.log('Got the following mongoose error: '+ err);
});
db.once('connected', function (condata) {
console.log('The bloody database is open!');
var writeStream = gfs.createWriteStream({
mode: 'w',
_id: cuID
});
console.log('And now lets write the thing');
readStream = fs.createReadStream(file);
readStream.pipe(writeStream);
writeStream.on('data', function (chunk){
console.log('Writing some data, just dont know what');
});
writeStream.on('end', function (filen) {
console.log('Written file ' + filen.name);
});
writeStream.on('error', function (err) {
console.log('Got the following error: ' + err);
});
});
}我仍然得到相同的问题,它等待数据库连接,连接上没有错误,但查看输出(还有一些其他代码来选择文件名,设置集合并生成uID,它并行地执行两个操作,但是,将其设置为只做一没有区别)
Will create id 553f39448c80bd9e7e6d904e in the collection fsImage and store ./data/kick.jpg
Will create id 553f39448c80bd9e7e6d904f in the collection fsSound and store ./data/kick-808.wav
The bloody database is open!
And now lets write the thing
The bloody database is open!
And now lets write the thing仍然没有什么东西可以开始写
发布于 2015-04-28 23:45:42
经过很多努力,以及一些比我强得多的人的大力帮助,这个问题终于出现了。writeStream不会发出"end",只会发出"finish",因此要修复代码,所有需要更改的内容都是
writeStream.on('end', function (filen) {
console.log('Written file ' + filen.name);
});至
writeStream.on('finish', function (filen) {
console.log('Written file ' + filen.name);
});发布于 2016-08-10 15:26:52
writeStream.on('close', function (file){ console.log(file.filename, 'write to database'); });
您在文件集合中的文件名是(filename)而不是( name )。并使用close事件
https://stackoverflow.com/questions/29910794
复制相似问题