Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

javascript - 阅读Node.js中的Promise of Promise属性(Read Props of Promise of Stream in nodejs)

basically what I want to achieve is check in a middleware whether an uploaded file has the correct image type (png for example).

(基本上,我要实现的是在中间件中检查上传的文件是否具有正确的图像类型(例如png)。)

This is what I have come up with till now:

(到目前为止,这是我想出的:)

export const fileCheckMiddleware = (req, res, next) => {
  const acceptedImageTypes = ["image/gif", "image/jpeg", "image/png"];

  const oldWrite = res.write;
  const oldEnd = res.end;

  const chunks = [];

  res.write = (...restArgs) => {
  chunks.push(new Buffer(restArgs[0]));
  oldWrite.apply(res, restArgs);
 };

  res.end = async (...restArgs) => {
if (restArgs[0]) {
  chunks.push(new Buffer(restArgs[0]));
}

const body = Buffer.concat(chunks).toString("utf8");

try {
  let parsedBody = {};
  try {
    parsedBody = JSON.parse(body);
  } catch (err) {
    parsedBody = { data: { unparsedBody: body } };
  }

  const { variables } = req.body;

  console.log("x1b[1m%sx1b[0m", "LOG variables", variables.file);
  if (variables.file) {
    console.log("x1b[1m%sx1b[0m", "LOG type", typeof variables.file);
  }
} catch (err) {}
oldEnd.apply(res, restArgs);
   };
  next();
};

The logged type of variables.file is an object.

(记录的variables.file类型是一个对象。)

And the result of the console.log is this:

(而console.log的结果是这样的:)

LOG variables Promise {
 { filename: 'trump.jpeg',
   mimetype: 'image/jpeg',
   encoding: '7bit',
   createReadStream: [Function: createReadStream] } }

So how can I access the mimetype here?

(那么我如何在这里访问mimetype?)

I tried to map over the keys, variables.file["Promise"],...

(我试图映射键,variables.file [“ Promise”],...)

  ask by Gh05d translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Promise is not a key of variables.file , it's the type of variables.file .

(Promise是不是一个关键variables.file ,它的类型variables.file 。)

That means your code starts executing as soon as the HTTP request starts, and the file is received asynchronously, so you have to do something like:

(这意味着您的代码将在HTTP请求启动后立即开始执行,并且文件是异步接收的,因此您必须执行以下操作:)

variables.file.then(file => {
    // Do whatever you want with the file
    next();
});

Or declare the surrounding function as async and do this:

(或者将周围的function声明为async并执行以下操作:)

const file = await variables.file;
// Do whatever you want with the file
next();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...