0

我尝试将 readStream (Image) 转换为字符串,然后将其存储在 Redis 中。然后从 Redis 中检索字符串并将其转换回 readStream。但它没有成功。

function getFile(fileKey) {
  console.log(fileKey);
  const downloadParams = {
    Key: fileKey,
    Bucket: bucketName,
  };

  return s3.getObject(downloadParams).createReadStream();
}

exports.getFile = getFile;

为了将流转换为字符串,我使用的是流到字符串。它被转换并存储在 Redis 中。

const { getFile } = require("../s3");
const redis = require("redis");

const client = redis.createClient();

var toString = require("stream-to-string");

exports.getFileFromS3Controller = async (req, res) => {
  console.log(req.params);
  const path = req.params.path;
  const key = req.params.key;
  const readStream = getFile(path + "/" + key);

  toString(readStream).then(function (msg) {
    // Set data to Redis
    client.setex(key, 3600, msg);
  });

  readStream.pipe(res);
};

在从 Redis 检索时,我没有得到它。

const redis = require("redis");
const client = redis.createClient(null, null, { detect_buffers: true });
const Readable = require("stream").Readable;

// Cache middleware
function cache(req, res, next) {
  const { path, key } = req.params;

  client.get(key, (err, data) => {
    if (err) throw err;

    if (data !== null) {
      var s = new Readable();
      s.push(data);
      s.push(null);
      s.pipe(res);
    } else {
      next();
    }
  });
}

router.get("/:path/:key", cache, getFileFromS3Controller);
4

1 回答 1

0

你没有打电话给下一个。另一个错误是流没有保存在 req 中的任何位置,因此您可以稍后从控制器访问。据我所知,您直接在 res 中编写它是一个问题,因为在此之后您不能再使用 res 发送任何其他内容。

这是代码(未测试)

exports.getFileFromS3Controller = (req, res) => {
  if (req.fileStream) {
      req.fileStream.pipe(res);
      return
  }

  console.log(req.params);
  const path = req.params.path;
  const key = req.params.key;
  const readStream = getFile(path + "/" + key);

  toString(readStream).then(function (msg) {
      // Set data to Redis
      client.setex(key, 3600, msg);

      // Conver string to readable
      const readable = new Readable();
      readable.push(msg);
      readable.push(null);
      readable.pipe(res);
  });
};

function cache(req, res, next) {
    const { path, key } = req.params;

    client.get(key, (err, data) => {
        if (err) throw err;

        if (data !== null) {
            var s = new Readable();
            s.push(data);
            s.push(null);

            req.fileStream = s;
        }

        next();
    });
}

编辑我修复了答案中的一个错误,因为无法倒带可读流。

于 2021-06-04T18:32:57.683 回答