2

I have a shiny app to generate a .txt file to download. In addition, I would like to keep a copy of the file that users generate in my shiny server. the server function looks like :

server <- function(input, output, session){

data_gen <- reactive({

d1= data.frame(...)
d2= data.frame(...)

result <- list(d1=d1, d2=d2) 
return(result)

})

create_file <- reactive({
 sink("/srv/shiny-server/S3/file.txt",append = TRUE)
 print(data_gen()$d1) 
 print(data_gen()$d2)
 sink()

})

output$downloadData <- downloadHandler(

  filename = function() {"input.txt"},
  content = function(file) {

      sink(file,append = TRUE)

    print(data_gen()$d1) 
    print(data_gen()$d2)

      sink()
  }
)


}

I'm able to download the data but the app does not react to the create_file function and it does not write a copy into shiny server. Any Idea how could I fix this ?

Haribo
  • 2,071
  • 17
  • 37

1 Answers1

3

Your create_file function is a reactive. Reactive functions only evaluate when 1) their output is required, and 2) their inputs have changed. Neither appears to apply here.

What you could do is move the contents of create_file inside your downloadhandler. content must receive a function that returns a file, but the function can do other things first. So try the following:

server <- function(input, output, session){

    data_gen <- reactive({
        d1= data.frame(...)
        d2= data.frame(...)
        result <- list(d1=d1, d2=d2) 
        return(result)
    })

    output$downloadData <- downloadHandler(

        filename = function() {"input.txt"},
        content = function(file) {

        # save non-user copy
        sink("/srv/shiny-server/S3/file.txt",append = TRUE)
        print(data_gen()$d1) 
        print(data_gen()$d2)
        sink()

        # copy to be returned for user
        sink(file,append = TRUE)
        print(data_gen()$d1) 
        print(data_gen()$d2)
        sink()
    })
}
Simon.S.A.
  • 6,240
  • 7
  • 22
  • 41