· r-2

R: Rook - Hello world example - 'Cannot find a suitable app in file'

I’ve been playing around with the Rook library and struggled a bit getting a basic Hello World application up and running so I thought I should document it for future me.

I wanted to spin up a web server using Rook and serve a page with the text 'Hello World'. I started with the following code:

library(Rook)
s <- Rhttpd$new()

s$add(name='MyApp',app='helloworld.R')
s$start()
s$browse("MyApp")

where helloWorld.R contained the following code:

function(env){
  list(
    status=200,
    headers = list(
      'Content-Type' = 'text/html'
    ),
    body = paste('<h1>Hello World!</h1>')
  )
}

Unfortunately that failed on the 's$add' line with the following error message:

> s$add(name='MyApp',app='helloworld.R')
Error in .Object$initialize(...) :
  Cannot find a suitable app in file helloworld.R

I hadn’t realised that you actually need to assign that function to a variable 'app' in order for it to be picked up:

app <- function(env){
  list(
    status=200,
    headers = list(
      'Content-Type' = 'text/html'
    ),
    body = paste('<h1>Hello World!</h1>')
  )
}

Once I fixed that everything seemed to work as expected:s

> s
Server started on 127.0.0.1:27120
[1] MyApp http://127.0.0.1:27120/custom/MyApp

Call browse() with an index number or name to run an application.
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket