限制下载次数
Limit the number of downloads
我是使用 mongoDB 和 node.js 的新手,我试图限制服务器中每个文件的下载数量。我正在使用 gridfs 将文件存储在数据库中,并在生成 link 之后能够下载文件,我需要限制每个文件的下载数量,但不知道如何去做。
假设您使用 express 作为 node.js http 服务器,您可以这样做:
const app = require('express')();
const bucket = new mongodb.GridFSBucket(db, {
chunkSizeBytes: 1024,
bucketName: 'songs'
});
const downloads = {};
const fileURI = '/somefile.mp3';
const maxDownload = 100;
app.get(fileURI, function(req, res) {
if (downloads[fileURI] <= maxDownload) {
// pipe the file to res
return bucket.openDownloadStreamByName('somefile.mp3').
.pipe(res)
.on('error', function(error) {
console.error(error);
})
.on('finish', function() {
console.log('done!');
downloads[fileURI] = downloads[fileURI] || 0;
downloads[fileURI]++;
});
}
return res.status(400).send({ message: 'download limit reached' });
});
app.listen(8080);
我是使用 mongoDB 和 node.js 的新手,我试图限制服务器中每个文件的下载数量。我正在使用 gridfs 将文件存储在数据库中,并在生成 link 之后能够下载文件,我需要限制每个文件的下载数量,但不知道如何去做。
假设您使用 express 作为 node.js http 服务器,您可以这样做:
const app = require('express')();
const bucket = new mongodb.GridFSBucket(db, {
chunkSizeBytes: 1024,
bucketName: 'songs'
});
const downloads = {};
const fileURI = '/somefile.mp3';
const maxDownload = 100;
app.get(fileURI, function(req, res) {
if (downloads[fileURI] <= maxDownload) {
// pipe the file to res
return bucket.openDownloadStreamByName('somefile.mp3').
.pipe(res)
.on('error', function(error) {
console.error(error);
})
.on('finish', function() {
console.log('done!');
downloads[fileURI] = downloads[fileURI] || 0;
downloads[fileURI]++;
});
}
return res.status(400).send({ message: 'download limit reached' });
});
app.listen(8080);