JavaScript检查文件大小是否超过25mb

时间:2020-07-27 04:25:33

标签: javascript node.js

检查文件大小是否大于25mb,并引发错误。我认为下面的代码存在一些故障。帮助将不胜感激。

#Snippet 1

const checkSize = () => async (data) => {
  // eslint-disable-next-line no-use-before-define
  const filesize = formatBytes(data.filesize);

  if (filesize > 2.5e+7) {
    throw new errors.BadRequest('exceeded the limit');
  }

#snippet 2

const formatBytes = (bytes, decimals = 2) => {
  if (bytes === 0) {
    return '0 Bytes';
  }

  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  // const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

  const i = Math.floor(Math.log(bytes) / Math.log(k));

  // eslint-disable-next-line no-restricted-properties
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))}`;
};

0 个答案:

没有答案