Express 'response.download' 为同一请求返回非标准数据

Express 'response.download' returning non-standard data for the same request

我正在生成一个下载文件,每次发送请求时,return对我来说都是不同的,每次都按预期生成文件:

usuário,primeiro_nome,ultimo_nome,ativo,completou_o_treinamento
4,Foo,Bas,SIM,SIM
5,Ble,Loco,NÃO,NÃO
9,gui2,md,NÃO,NÃO
3137,foo,baz,NÃO,NÃO

但表达 returns 不一样,它应该 return response.download 中的文件,但有时当我打电话时,returns File not found 其他时候 return 只是字段 usuário,primeiro_nome,ultimo_nome,ativo,completou_o_treinamentono body response 有时 return 应该是文件,我不知道哪里出了问题,因为文件总是以正确的方式生成

生成文件代码

export const createReportFile = ({ reportLines, fromDate, toDate }: CreateReportProps): string => {
  const startDate = format(fromDate, 'dd-MM-yyyy')
  const endDate = format(toDate, 'dd-MM-yyyy')
  const aksReportDate = Date.now()

  const reportFileId = `${startDate}-to-${endDate}Report${aksReportDate}`

  const reportFileStream = fs.createWriteStream(
    path.join(__dirname, '..', '..', '..', 'tmp', 'uploads', `${reportFileId}.csv`),
  )

  const fieldsLine = 'usuário,primeiro_nome,ultimo_nome,ativo,completou_o_treinamento'

  reportFileStream.once('open', () => {
    reportFileStream.write(fieldsLine + '\r\n')
    reportLines.forEach(({ user_id, first_name, last_name, active, completed }) => {
      reportFileStream.write(`${user_id},${first_name},${last_name},${active},${completed}\r\n`)
    })
  })

  return reportFileId
}

下载文件代码


.
.
.
    const usersReport = ....generate users report


    const reportFileId = createReportFile({ fromDate, toDate, reportLines: usersReport })

    const filePath = path.join(__dirname, '..', '..', '..', 'tmp', 'uploads', `${reportFileId}.csv`)

    console.log(filePath)

    return response.download(filePath)
  }

用户报告

[
  {
    user_id: 4,
    first_name: 'foo',
    last_name: 'baz',
    active: 'SIM',
    completed: 'SIM'
  },
  {
    user_id: 5,
    first_name: 'Ble',
    last_name: 'L',
    active: 'NÃO',
    completed: 'NÃO'
  },
  {
    user_id: 9,
    first_name: 'foooo',
    last_name: 'ma',
    active: 'NÃO',
    completed: 'NÃO'
  },
  {
    user_id: 3,
    first_name: 'foo',
    last_name: 'bar',
    active: 'NÃO',
    completed: 'NÃO'
  }
]

找到解决方案

我已将 generate file code 更改为以下代码

export const createReportFile = ({ reportLines, fromDate, toDate }: CreateReportProps): string => {
  const startDate = format(fromDate, 'dd-MM-yyyy')
  const endDate = format(toDate, 'dd-MM-yyyy')
  const aksReportDate = Date.now()

  const reportFileId = `${startDate}-to-${endDate}Report${aksReportDate}`

  let data = 'usuário,primeiro_nome,ultimo_nome,ativo,completou_o_treinamento\r\n'

  reportLines.forEach(({ user_id, first_name, last_name, active, completed }) => {
    data += `${user_id},${first_name},${last_name},${active},${completed}\r\n`
  })

  fs.writeFileSync(
    path.join(__dirname, '..', '..', '..', 'tmp', 'uploads', `${reportFileId}.csv`),
    data,
  )

  return reportFileId
}

我不是专家,不知道为什么在我更改时它会起作用,但我相信是因为在以前的解决方案中我使用的是流,现在我们同步写入文件

如果我错了请指正,我想了解更多这方面的信息