adamgibbons / ics

iCalendar (ics) file generator for node.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Downloading .ics file

tjin88 opened this issue · comments

How would you download a .ics file? Is there a built-in method I can use, or should I use the buildEvent method to return a string, then convert to .ics myself?

If you're using something like Express with a REST endpoint, your final response will be something like this:

res
.set(
'Content-Disposition',
'attachment; filename="${FILE_NAME}.ics"',
)
.set('Content-Type', 'text/calendar')
.status(200)
.send(ics);
}

They key is to set your HTTP headers so clients know how to handle the response (in this case, an ics text file).

The ics is either generated in a function prior to the final response code above, or perhaps loaded from a cached source (in the case of a feed you probably don't want to regenerate it on every request, so you have other mechanisms to update the feed snapshot).

For the use case where you're generating client side, you can use the popular library downloadjs or create a simple utility function.

  function downloadFile(config: { fileContents: any; fileName: string; mimeType: string }) {
    const { mimeType, fileContents, fileName } = config
    const blob = new Blob([fileContents], { type: mimeType })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.setAttribute('href', url)
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
  
  // ...
downloadFile({
    mimeType: 'text/calendar',
    fileContents: value,
    fileName: 'meeting.ics',
})