限制下载次数

时间:2017-09-28 11:23:13

标签: javascript node.js mongodb gridfs

我真的很新用mongoDB和node.js,我试图限制我服务器中每个文件的下载次数。我使用gridfs存储数据库上的文件,生成链接后可以下载文件我需要限制每个文件的下载次数,但不知道如何操作。

1 个答案:

答案 0 :(得分:1)

假设你使用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);
相关问题