gpt4 book ai didi

node.js - 使用 gridfs-stream 将字符串写入 gridfs

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:39 24 4
gpt4 key购买 nike

我通过代码片段将文件写入gridfs,但我无法找到将字符串更新到Gridfs的写入方法。

下面的代码片段将使用路径进行更新,但是直接字符串缓冲区怎么样?

var metadata = {
"path": path
};
var writestream = gfs.createWriteStream({
filename: name,
mode: 'w',
content_type: type,
metadata: metadata
});
fs.createReadStream(path).pipe(writestream);
// var buf = new Buffer("hello");
writestream.on('close', function (file) {
console.log("Gridfs created");
});

最佳答案

当搜索如何使用 NodeJS 在 Mongo GridFS 中存储字符串数据时,首先出现此页面。由于这里和其他地方的大多数答案都基于已弃用的 API,因此我决定发布基于更新的 GridFSBucket 的代码。该代码还提供了覆盖现有文件的附加功能。如果您不需要 - 您可以将 openUploadStreamWithId 替换为 openUploadStream ,这会创建重复项。

var mongo = require('mongodb');
var stream = require('stream');
var MongoClient = mongo.MongoClient;

function getFileSystemItem(dbo, filename) {
var buf = new Buffer('');
return new Promise(function(resolve, reject) {
var bucket = new mongo.GridFSBucket(dbo);
var readstream = bucket.openDownloadStream(filename);
readstream.on('data', (chunk) => {
buf = Buffer.concat([buf, chunk]);
});
readstream.on('error', (err) => {
reject(err);
});
readstream.on('end', () => {
var res = buf.toString();
buf = null; // Clean up memory
readstream.destroy();
resolve(res);
});
});
}

function putFileSystemItem(dbo, filename, data) {
var putItemHelper = function(bucket, resolve, reject) {
var writeStream = bucket.openUploadStreamWithId(filename, filename);
var s = new stream.Readable();
s.push(data);
s.push(null); // Push null to end stream
s.pipe(writeStream);
writeStream.on('finish', resolve);
writeStream.on('error', reject);
};
return new Promise(function(resolve, reject) {
var bucket = new mongo.GridFSBucket(dbo);
bucket.find({_id: filename}).count(function(err, count) {
if (err) return reject(err);
if (count > 0) {
bucket.delete(filename, function() {
putItemHelper(bucket, resolve, reject);
}, reject)
} else {
putItemHelper(bucket, resolve, reject);
}
}, reject);
});
}

function test() {
var MongoUrl = 'mongodb://localhost:27017';
var dbName = 'test';
MongoClient.connect(MongoUrl, function(err, db) {
if (err) throw err;
var dbo = db.db(DbName);
putFileSystemItem(dbo, 'test', 'this is a test')
.then(function(a) {
console.log('Wrote a gridFS file with metadata:', a);
return getFileSystemItem(dbo, 'test')
})
.then(function(a) {
console.log('Got data back from a gridFS file:', a);
db.close();
})
.catch(function(e) {
console.log(e);
db.close();
})
});
}
test();

鸣谢:这是由十几个其他 StackOverflow 页面和 MongoDB API 帮助汇总而成。

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

24 4 0