gpt4 book ai didi

node.js - 将流写入 gridfs-stream

转载 作者:太空宇宙 更新时间:2023-11-04 02:26:47 25 4
gpt4 key购买 nike

一直在努力尝试让网格(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);

但是,如果运行上面的代码,它会创建文件,但(据我所知)永远不会到达关闭语句 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

还没开始写

最佳答案

经过一番折腾,并得到了比我更好的人的大力帮助,问题被发现了。writeStream 不会发出“结束”,只会发出“完成”,因此要修复代码,需要更改的就是

writeStream.on('end', function (filen) {
console.log('Written file ' + filen.name);
});

writeStream.on('finish', function (filen) {
console.log('Written file ' + filen.name);
});

关于node.js - 将流写入 gridfs-stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29910794/

25 4 0