express icon indicating copy to clipboard operation
express copied to clipboard

res.download() produces blank file

Open charlieroth opened this issue 6 years ago • 5 comments

I am attempting to generate a CSV file and download it into my React application. Whenever I hit this endpoint the browser always downloads a blank file but when I open it with open filename.csv , it has the data as expected. I don't know if this is on the React end or on the express end but I figured I would start here.

My thoughts are that it has to do with me using os.tmpdir() but it runs as if it succeeds so no helpful debug. I logged the csvStream.on("data") event and it was writing to the file properly. It seems that res.download() does not like the directory it is reading from. Can this be confirmed? Would a directory like /var/folders/j_/43f_ppvn1y5_w7h24ng8yq440000gn/T/node-lab.csv cause res.download() to produce a blank file?

node: 14.3.0
express: ^4.17.1
react: ^16.13.1
react-dom: ^16.13.1

router.ts

router.get("/gen-csv", async (_req: Request, res: Response) => {
  const mockColumns = getMockColumns();
  const headerRow = mockColumns.map((col) => col.fullName);
  const filepath = path.resolve(os.tmpdir(), "node-lab.csv")
  console.log("filepath: ", filepath)
  const fileWriteStream = fs.createWriteStream(filepath)
  const csvStream = format({headers: headerRow})
  csvStream.pipe(fileWriteStream)

  const rows = ["fullName", "jobTitle", "jobArea", "jobType"]
  rows.forEach((row: string) => {
    const templateRow = mockColumns.reduce((acc: any, col: MockColumn) => {
      return {...acc, [col.fullName]: col[row]}
    }, {})
    csvStream.write(templateRow)
  })

  // close csvStream
  // ...

  res.download(filepath, "node-lab.csv", (err: Error) => {
    if (err) {
      console.error(err)
    } else {
      console.log("Generated CSV!!")
    }
  })
})

server.ts

import express from "express"
import cors from "cors"
import http from "http"
import morgan from "morgan"
import bodyParser from "body-parser"
import {createTerminus} from "@godaddy/terminus"
import router from "./router"

const PORT = process.env.PORT || 4000
const app = express()

app.use(cors())
app.use(morgan("dev"))
app.use(bodyParser.json())
app.use(router);

// godaddy/terminus stuff ...

server.listen(PORT, () => {
  console.log("Server listening on port http:localhost:4000")
})

App.js

import React from "react"

function App() {
  const [loading, setLoading] = React.useState(false)

  const handleGenerateCSV = async (e) => {
    e.preventDefault()
    const res = await fetch("http://localhost:4000/gen-csv")
    const blob = await res.blob()
    const url = window.URL.createObjectURL(new Blob([blob]))
    const link = document.createElement("a")
    link.href = url
    link.setAttribute("download", "node-lab.csv")
    document.body.appendChild(link)
    link.click()
    link.parentNode.removeChild(link)
    setLoading(false)
  }

  const isLoading = () => {
    if (loading) return <h3>Loading...</h3>
    else return null;
  }

  return (
    <>
      <h1>React Lab</h1>
      <button onClick={(e) => {
        setLoading(true)
        handleGenerateCSV(e)
      }}>Generate CSV</button>
      {isLoading()}
    </>
  )
}

export default App

When I log the blob this is the result:

Blob {
  size: 0, 
  type: "text/csv"
}

charlieroth avatar May 24 '20 04:05 charlieroth

ok, so firstly thank you for providing some code. That is always useful. What I believe your question is

  • is using a temp folder an issue?
  • does res.download work?

So my first advice is to create a local csv, hard code the res.download to use it and see if that works.

ghinks avatar May 24 '20 13:05 ghinks

Here is a working and complete example of res.download

I do not believe your issue is with express. But a regular coding issue associated with streams and files.

If you isolate the expressJS part and give a full and complete but minimal working demonstration of your code it would be possible to debug.

( did you completely flush your streams?)

Then as you have said this is a temp file or streams flushing issue.

In general this repo is for expressjs issues and not general coding questions.

Do you think this is a general app question and not an express question.

If so please give me a nice smiley face, close this issue, and do try stack overflow. We should be the place of last resort for express application coding questions.

ghinks avatar May 24 '20 13:05 ghinks

Moved to: Stack Overflow

charlieroth avatar May 24 '20 14:05 charlieroth

Hi, Were you able to find a solution for this ? I am also facing the same error.

ankit49 avatar Feb 11 '22 13:02 ankit49

Same issue, is there a solution available??, if i use JSON.stringify while blob creation it works but still the CSV generated is not correct

monika-pant avatar Jun 10 '24 06:06 monika-pant