GithubHelp home page GithubHelp logo

yihui / servr Goto Github PK

View Code? Open in Web Editor NEW
269.0 19.0 34.0 474 KB

A simple HTTP server in R

Home Page: https://cran.rstudio.com/package=servr

R 94.87% Makefile 0.31% HTML 1.98% JavaScript 2.84%
r r-package web-server http-server websocket

servr's Introduction

servr

R-CMD-check CRAN release

A simple HTTP server to serve files under a given directory based on the httpuv package.

You can install this package from CRAN (stable version) via install.packages('servr') or r-universe.dev (development version).

This package is licensed under GPL.

Serve static files

To some degree, this package is like python -m SimpleHTTPServer or python -m http.server. It may be used to serve:

You can either run servr::httd() in an interactive R session, or run from command line:

# default: port 4321, do not launch browser
Rscript -e "servr::httd()"

# open a web browser
Rscript -e "servr::httd()" -b

# listen on port 4000
Rscript -e "servr::httd()" -p4000

# pass arguments to the httd() function
Rscript -e "servr::httd(,4000,TRUE)"

There is also a shell script under system.file('bin', package = 'servr'); if it is added to PATH, you can simply run

servr  # serve the current directory
servr -b  # launch the browser
servr -b -p4000  # change port to 4000

Serve and watch a directory

Similar to httd(), the function httw() can both serve and watch a directory. If you are viewing an HTML file in the browser, it will be automatically refreshed whenever there are any changes in the directory (e.g. you added, deleted, or modified certain files in the directory).

Serve dynamic documents

Besides httd(), there are functions jekyll(), rmdv1(), and rmdv2() in this package to serve HTML files generated from R Markdown documents (via knitr or rmarkdown). R Markdown documents can be automatically re-compiled when their HTML output files are older than the corresponding source files, and HTML pages in the web browser can be automatically refreshed accordingly, so you can focus on writing R Markdown documents, and results will be updated on the fly in the web browser. This is even more useful when you write R Markdown documents in the RStudio IDE, because the HTML files are displayed in the RStudio viewer pane, and you can put the source document and its output side by side.

Jekyll with servr and knitr

Serve package vignettes

The function vign() can be used to serve R Markdown/HTML package vignettes. The HTML output files are generated and displayed in the web browser so you can preview the vignettes, and they will be cleaned up after they are loaded in the web browser to make sure your source package is clean.

Daemonized server

All server functions can be used in the daemonized mode, i.e., they can be non-blocking in the R session, which allows you to continue working in the R console after the server is launched. This mode can be set via the argument daemon = TRUE in most server functions. See ?server_config for more information.

servr's People

Contributors

cderv avatar cpsievert avatar feddelegrand7 avatar fkohrt avatar jasonpunyon avatar jessjaco avatar marcinkosinski avatar ramnathv avatar raymondben avatar rekado avatar rlesur avatar torfason avatar yihui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

servr's Issues

"auto_ptr" deprecation warning on installation

I'm new to Ubuntu (from Win10).
I've got an existing bookdown project that I'm trying to work on from my Ubuntu machine.

platform: x86_64-pc-linux-gnu
Ubuntu 20.04 LTS

Prior to installing servr, the following were installed:

r-base 3.6.3-2
rstudio:amd64 1.2.5042
tinytex 0.22
bookdown 0.18

The version of servr is:
servr 0.16

During the install, done from inside an R session with install.packages("servr"), it took a long time and there were many many deprecation warnings about "auto_ptr"

It did eventually install.

File Path issue with servr::jekyll

When converting from Rmd -> md files the file path for figures is missing a /

this does not occur when calling servr::jekyll() from an R session, however if one calls jekyll serve from bash, one cannot find the image.

looking at the md file I notice this:

![plot of chunk unnamed-chunk-1](/mysitefigure/source/2016-04-17-test/unnamed-chunk-1-1.png)

whereas the code should read:

![plot of chunk unnamed-chunk-1](/mysite/figure/source/2016-04-17-test/unnamed-chunk-1-1.png)

If I manually change the md file, this issue goes away

Start a server without launching browser

Hi, everyone.

I have a local folder created with LDAvis, This folder has four files: "d3.v3.js" "index.html", "lda.css", "lda.json" "ldavis.js" (local folder is d <- "C:\Users\msgc\AppData\Local\Temp\RtmpMBtR5L\file53d47f732b79"
file53d47f732b79.zip

Executing servr::httd(d) to the local folder works great. The issue is that I am packaging this process with an electron-quick-start. When I execute the httd(d) function it creates the server but the application stops (maybe because is not interactive).

Is there a way to start the server with http(d) in the background (without trying to launch a browser) and then use the resulting url with the browseURL? I am thinking something like:
utils::browseURL(httd(d)$url)

Thank you so much in advance.

Add make support

i.e. if there's a makefile in the directory, run make every x seconds.

trouble debugging daemon=TRUE

I cannot get my site to load when I use daemon=TRUE and I'm not sure how to debug this one. If I omit that option, everything works just swanky.

If I include daemon=TRUE, the site still builds as before, I get the identical terminal output plus the additional line:

To stop the server, run servr::daemon_stop("35325888") or restart your R session

and of course I get my command prompt back, but as far as I can tell the server isn't running. Am I missing something or is daemon=TRUE not compatible with servr::jekyll? fwiw, my site source is here https://github.com/cboettig/2015.

inf_mr() opening new instances when saving .Rmd file in R Studio

Thanks for this cool tool! Used it successfully at a group meeting yesterday. It's a bit quirky, but I can see myself saving time in the future. Here's a small bug report for an otherwise useful too. I hope it becomes more developed over time.

System: Mac M1 OSX 12.4 (Monterey)
R-Studio 2022.07.0 Build 548
Xaringan Versino: 0.25.2

When launching inf_mr() to visualize live editing of a .Rmd file for presentations inside of R-studio, the first instance runs in the viewer of R-studio. The second instance opens in a browser windows (e.g. Chrome) which is a good for 2nd monitor presentations. When saving the .Rmd file after making changes because inf_mr() doesn't update r code blocks for live editing/visualization, the browser opens up ANOTHER tab to the exact same address:port (e.g. ...
http://127.0.0.1:4321/YourXaringanPresntation.html?viewer_pane=1&capabilities=1&host=http%#A%#A%#A%#A%#A etc... )

This causes strange syncing issues between multiple tabs when trying to run the slide presentation (i.e. next slide forces back one slide from another tab - i.e. slides presentation becomes 'sticky') from one of the browser tabs or R-studio viewer, but is solved by closing all but one tab and time.

Fatal Error on OSX El Capitan

Hi There -

Thanks very much for the package. It looks like it will be really useful once I'm able to get it working.

Unfortunately, I'm encountering a fatal error when using the servr::jekyll() command. My jekyll site is simply a clone of your knitr-jekyll example. After cloning I set the working directory to the knitr-jekyll folder and run servr::jekyll(). This results in an error with the following stack trace:

 *** caught segfault ***
address 0x18, cause 'memory not mapped'

Traceback:
 1: .Call("httpuv_makeTcpServer", PACKAGE = "httpuv", host, port,     onHeaders, onBodyData, onRequest, onWSOpen, onWSMessage,     onWSClose)
 2: makeTcpServer(host, port, appWrapper$onHeaders, appWrapper$onBodyData,     appWrapper$call, appWrapper$onWSOpen, appWrapper$onWSMessage,     appWrapper$onWSClose)
 3: httpuv::startServer(host, port, list())
 4: doTryCatch(return(expr), name, parentenv, handler)
 5: tryCatchOne(expr, names, parentenv, handlers[[1L]])
 6: tryCatchList(expr, classes, parentenv, handlers)
 7: tryCatch(expr, error = function(e) {    call <- conditionCall(e)    if (!is.null(call)) {        if (identical(call[[1L]], quote(doTryCatch)))             call <- sys.call(-4L)        dcall <- deparse(call)[1L]        prefix <- paste("Error in", dcall, ": ")        LONG <- 75L        msg <- conditionMessage(e)        sm <- strsplit(msg, "\n")[[1L]]        w <- 14L + nchar(dcall, type = "w") + nchar(sm[1L], type = "w")        if (is.na(w))             w <- 14L + nchar(dcall, type = "b") + nchar(sm[1L],                 type = "b")        if (w > LONG)             prefix <- paste0(prefix, "\n  ")    }    else prefix <- "Error : "    msg <- paste0(prefix, conditionMessage(e), "\n")    .Internal(seterrmessage(msg[1L]))    if (!silent && identical(getOption("show.error.messages"),         TRUE)) {        cat(msg, file = stderr())        .Internal(printDeferredWarnings())    }    invisible(structure(msg, class = "try-error", condition = e))})
 8: try(httpuv::startServer(host, port, list()), silent = TRUE)
 9: port_available(p, host)
10: random_port(4321L)
11: server_config(dir, ..., baseurl = baseurl)
12: dynamic_site(dir, ..., build = function(...) {    update = build_all()    if (update || !file_test("-d", destination))         jekyll_build()    update}, site.dir = destination, baseurl = baseurl)
13: servr::jekyll()

My sessionInfo is:

R version 3.3.1 (2016-06-21)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.11.5 (El Capitan)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] rsconnect_0.4.3 tools_3.3.1   

Any help would be greatly appreciated.

-Jay

fail to autogenerate .md file

Hi, yihui:

I want to report that servr::jekyll() can't auto-generate .md file here. I followed your suggestion that put .rmd file into an independent folder "_resource", but servr cannot autogenerate any .rmd files in that folder. However, if I move the .rmd file into the root folder, it works. Please let me know if you have any idea of what happen here. Thanks!

P.S., I actually using servr::jekyll(command = "bundle exec jekyll build"); servr::jekyll() does not work here.

Use Perl-like regex for file matching

I'm attempting to use a Docker container hosting a servr server serving a CRAN-like repository that monitors for changes and them automatically updates the PACKAGE files once a package is uploaded.

But unfortunately, the list.files() pattern argument uses the extended regex engine rather than Perl, meaning that you can't use negative look-around. The upshot being that servr monitors the repo, detects a change, runs the handler function which updates the PACKAGE files, but because I can't use the pattern parameter to exclude monitoring of files that match the "PACKAGE" name, servr detects another directory change and so runs the handler function again, which updates the PACKAGE files and so on...

If the pattern parameter for the httw function accepted Perl-like regex however, then I would be able to exclude monitoring of PACKAGE* files and we wouldn't see this loop. Enabling this would only require a single change to the watch_dir function:

...
    info = file.info(list.files(
      dir, pattern, all.files = all_files, full.names = TRUE, recursive = TRUE,
      no.. = TRUE
    ))[, 'mtime', drop = FALSE]
...

would need to become

...
    files <- list.files(
      dir,
      all.files = all_files, full.names = TRUE, recursive = TRUE,
      no.. = TRUE
    )
    if (!is.null(pattern)){
      files <- grep(pattern,
                    files,
                    perl = TRUE,
                    value = TRUE
      )
    }
    info = file.info(files)[, 'mtime', drop = FALSE]
...

Happy to raise a PR if you're happy.

Unsafe ports list needs to be updated

While working on rstudio/pagedown#236, I've discovered that the list of unsafe ports has to be updated

servr/R/utils.R

Lines 175 to 176 in ab416b4

# exclude ports considered unsafe by Chrome http://superuser.com/a/188070
ports = sample(setdiff(3000:8000, c(3659, 4045, 6000, 6665:6669)), n)

For example, the port 6566 is now considered unsafe.
Will do a PR.

superfluous warning from random_port

Calling random_port() gives the warning createTcpServer: address already in use. I think that's kind of already known ... given that you are requesting a non-default port. The warning also causes confusion when a R_SERVR_PORT environment variable is found by httd:

> Sys.getenv('R_SERVR_PORT')
[1] "4169"
> servr::httd('/path')
createTcpServer: address already in use
To stop the server, run servr::daemon_stop(1) or restart your R session
Serving the directory /path at http://127.0.0.1:4169

The specified address was not already in use, it's just that random_port() got (un-lazily, for whatever reason) evaluated. Maybe an easy solution is to remove that warning?

Documentation unclear that deamon=TRUE will hang on requests from the same process

I ran into the issue that even though daemon=TRUE the session would hang on a request, but only when done within R. After some head scratching I realized that this is because although the server is running asynchronously, it is still within the same single threaded process as the console, so there is no way that the two can talk to each other. So in order to do this the server must be started in a new process. I've added to the documentation and will be submitting a pull request momentarily.

I would be glad if this is accepted in some form, because running into this can lead to some unneeded frustration. Of course, make any changes you feel are appropriate, or ask me to do so, or that it should be put elsewhere. I put the documentation into the documentation for the daemon parameter in server_config() because that is where I figured out how to start in daemon mode, so I'm guessing that people with my use case will read that part of the docs.

Thanks for the servr package, it is super helpful!

Could we set the files being rendered with rmdv2 ?

Right now rmdv2 build only Rmd files. I think it would be great we could render .R instead (I use .R files that I render because I like the way I can run source on the file). It might just be adding a pattern argument to rmdv2 that would default to ".Rmd". Would you accept a PR for this ?

Malformed Accept-Ranges Header

Problem

#41 introduced a malformed HTTP header by adding an unnamed item to the headers list.

servr/R/static.R

Lines 239 to 245 in 2cbd38a

list(
status = status, body = body,
headers = c(list('Content-Type' = type), if (status == 206L) list(
'Content-Range' = paste0("bytes ", range[2], "-", range[3], "/", file_size(path))
),
'Accept-Ranges: bytes') # indicates that the server supports range requests
)

Repro

  1. servr::httd('.', host = '0.0.0.0')
  2. Do a request to http://localhost:4321/ and pull the headers...
  3. The Accept-Ranges header is malformed.
    image

servr does not reclaim daemonised servers after deamon_stop()

My understanding of how deamon_stop() works is that it should reclaim the indexes of daemonised servers that have been stopped. This doesn't appear to happen when this workflow is followed:

  1. Download https://github.com/rstudio/bookdown-demo
  2. Launch the bookdown-demo.Rproj project
  3. Run the following
bookdown:::serve_book()
servr::daemon_stop(1)
bookdown:::serve_book()
servr::daemon_stop(1)
  1. Unexpectedly, the second serving of the book is hosted on deamonised server 2
servr::daemon_list()
# [1] 2

Is this expected behaviour?

Unicode not working in inf_mr()

---
title: "Xaringan inf_mr"
output: xaringan::moon_reader
---

無限 `r system2("python", c("-c", shQuote('print("月読")')), stdout = TRUE)`

If I render through rmarkdown::render I get the expected "無限 月読" but if I try to use inf_mr I just get this message and a blank output:

Warning message:
In grep("<!-- DISABLE-SERVR-WEBSOCKET -->", body, fixed = TRUE) :
  input string 1 is invalid in this locale

It seems like this is coming from here: 69f1279

I tried to adjust the locale settings, if I do Sys.setlocale("LC_ALL", "Ja_JP.UTF-8") it fixes the above issue but now it doesn't decode the stdout correctly, I get: 無限 <8c><8e><93>

Some more locale gymnastics within the document probably could fix that but I think dynamic_site shouldn't assume the body is in the system locale.

My OS locale is English display and shift-JIS codepage.

[ins] r$> sessionInfo()
R version 4.2.3 (2023-03-15 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 22621)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.932  LC_CTYPE=English_United States.932    LC_MONETARY=English_United States.932 LC_NUMERIC=C                          LC_TIME=English_United States.932    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] xaringan_0.28.1

loaded via a namespace (and not attached):
[1] compiler_4.2.3  fastmap_1.1.1   cli_3.6.0       htmltools_0.5.4 xfun_0.37       digest_0.6.31   rlang_1.1.0

Support for bundle in jekyll

I am requesting the addition of a use_bundle=TRUE or similar option for the jekyll function, to run eg bundle exec jekyll build instead of just jekyll build

How to use handler?

Hello, I want to run a command each time a file is changed but before httw() serves the files. I think the argument handler should be appropriate for that but I don't understand the second part of its description: "a function to be called every time any files are changed or added under the directory; its argument is a character vector of the filenames of the files modified or added".

So far, I'm doing something like:

servr::httw(
   "docs/site",
   handler = system("cd docs && mkdocs build -q")
)

This doesn't work and I couldn't find any example in the docs or online. Could you give an example of how to use it?

Thanks in advance

rmdv1/2 not detecting file changes when using RStudio server

I've started using servr for viewing live-updates to Rmd files in the RStudio preview pane while I edit. This works fine when I'm running on natively on OSX, but when I'm running RStudio Server via the browser there's no live update. It appears servr is not detecting file changes - the HTML is not re-compiled when I save an Rmd.

I've tried this running the RStudio Server on both on my own Ubuntu box and on the rocker/rstudio-daily:verse Docker image.

How to run server inside docker

I am using servr to serve leaflet tiles in a Shiny application :

deamon_id <- servr::httd(port = 8001, daemon = TRUE)

base_map <- leaflet() %>% 
    addTiles( urlTemplate = "http://localhost:8001/test/{z}_{x}_{y}.jpg")

The application works well locally. However when I dockerize and try to run it, the tiles don't show up. I guess this is because the dockerized version of the application is looking for a server running locally on 8001 which is obviously not the case. Is there any way I can overcome this problem?

websocket script is added to embedded iframes

If I am serving html through servr that embeds iframes, the iframe html also gets tagged with the websocket script. I think this can lead to conflicts wrt which websocket connection to honor (is the iframe reloaded or the page?).

library(servr)
library(htmltools)
tmpd <- tempdir()
httw(dir = tmpd, daemon = TRUE, pattern = "index.html")
save_html("iframecontent", file = file.path(tmpd, "iframe.html"))
save_html(tagList(tags$p("test1"), tags$iframe(src = "iframe.html")),
  file = file.path(tmpd, "index.html"))

Inspecting the served page:

untitled

In this situation, subsequent edits to index.html don't always guarantee a refresh of index.html.

nginx and initpath and baseurl, oh my

I don't know if you can help @yihui, but can't hurt to ask? I'm sorry I cannot think how to provide you a MWE...

I have RStudio Server running behind nginx proxy, so the url after logging in is "https://www.xyz.org/rstudio/"

I have a static site that I want to show in the RStudio viewer, so I proceed thusly:

> servr::httd('.', initpath = 'course', baseurl = '/rstudio')
To stop the server, run servr::daemon_stop(1) or restart your R session
Serving the directory /path/to/files at http://127.0.0.1:4321/rstudio/course

Well, okay, that looks not quite right. What's going to happen in the viewer? Oh ...

Not found:
./rstudio/course

But the site is working outside the viewer. I can open a tab and navigate to "https://www.xyz.org/rstudio/p/4321/course/" and the page is just as expected. How can I get it in the viewer?

servr::rmdv2(daemon=TRUE) crash in windows

Hi,
When I used servr::rmdv2(daemon=TRUE) command in Rstudio on Windows, It always made R session crashed after running 3 minitus. It display as "R Session Aborted. Rencoutered a fatal error. The session was teminnated." Please check this issues, Thanks.

jekyll() doesn't serve poole correctly

I'm getting redirect errors when I run jekyll() for a vanilla poole site [https://github.com/poole/poole]. If I run jekyll serve from terminal in the same directory it loads correctly. Error console in firefox says it's too many redirections.

servr::rmdv2 is blocking ?

Hello, I might have misunderstood but it seems running servr::rmdv2(host = "0.0.0.0", browser = FALSE, daemon = TRUE) is blocking the terminal it has been run in.

The following repex blocks when wait: TRUE (sorry I do not know how to escape the ` properly in github)
Is it normal behavior, I would expect the kniting to be done on a background thread ?

---
title: "My First R Markdown Document"
author: "Author: Your Name"
date: "Last update: `r format(Sys.time(), '%d %B, %Y')`"
output: html_document
params:
 wait: TRUE
---
Hello
\```{r, echo = params$wait, eval = params$wait}
Sys.sleep(15)
\```
Good bye

I run R 4.0.2 on centos7
I've made the following video to illustrate

servr

Redirect directories to ensure they end in /

This is pretty minor, but if you currently do to http://localhost:4321/subdir it serves subdir/index.html, but the links might not work because the directory is missing a trailing slash. Most web servers automatically redirect you to subdir/ to avoid this problem

Consider using httpuv's static file serving

rstudio/httpuv#177 was recently merged in to httpuv's master branch, and it might be useful for servr. It adds the ability to serve files from the filesystem from the background I/O thread using C++ only (no R), so it is faster than going through R, it will not be blocked by the main R thread, and it will not block the main R thread.

single quote doesn't work for Rscript on Windows 10

Rscript -e 'servr::httd("/directory/", port = 4000, host = "0.0.0.0")' with error

Error: unexpected end of input
Execution halted

Rscript -e "servr::httd('/directory/', port = 4000, host = '0.0.0.0')" works

rmd fails to compile when running servr::jekyll() - Windows10 - live updating doesn't work

I cloned the https://github.com/yihui/knitr-jekyll site. From there, I tried editing one of the RMD files for the blog post while running servr::jekyll() to watch it update in real time. When I do, I get the following error:

> servr::jekyll()
<simpleError: Failed to compile _source/2014-09-28-jekyll-with-knitr.Rmd>

* Retrying in 2 seconds...

After hitting STOP, I then get the next error message:

Warning message:
running command '"C:/PROGRA~1/R/R-33~1.0/bin/x64/Rscript" "build.R" "_source/2014-09-28-jekyll-with-knitr.Rmd" "_posts/2014-09-28-jekyll-with-knitr.md"' had status 1 

However, if I run system("jekyll b) to build the site and then run servr::jekyll() the files have been created and I can see the updates from RMD blog file. But I cannot seem to get this to work in real time.

Note: When running jekyll from a "Administrator Start Command Prompt with Ruby" (i.e. the Windows command window), I can run jekyll s, open a browser window at http://127.0.0.1:4000/knitr-jekyll// and then when I edit the MD files, I see real time updates to the website after refreshing the browser.

My sessionInfo() is:

> sessionInfo()
R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=English_United States.1252 
[2] LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets 
[6] methods   base     

loaded via a namespace (and not attached):
[1] rsconnect_0.4.2.2 tools_3.3.0       Rcpp_0.12.5      
[4] knitr_1.13        httpuv_1.3.3      mime_0.4         
[7] servr_0.4        
> 

I'm sure this is a Windows specific issue - perhaps something having to do with path assignments. I am running the following version of Ruby, jekyll and these gems:

C:\MyR\knitr-jekyll>ruby -v
ruby 2.2.4p230 (2015-12-16 revision 53155) [x64-mingw32]

C:\MyR\knitr-jekyll>gem list

*** LOCAL GEMS ***

bigdecimal (1.2.6)
colorator (0.1)
ffi (1.9.10 x64-mingw32)
io-console (0.4.3)
jekyll (3.1.6)
jekyll-sass-converter (1.4.0)
jekyll-watch (1.4.0)
json (1.8.1)
kramdown (1.11.1)
liquid (3.0.6)
listen (3.0.8)
mercenary (0.3.6)
minitest (5.4.3)
power_assert (0.2.2)
psych (2.0.8)
rake (10.4.2)
rb-fsevent (0.9.7)
rb-inotify (0.9.7)
rdoc (4.2.0)
rouge (1.11.1)
safe_yaml (1.0.4)
sass (3.4.22)
test-unit (3.0.8)
wdm (0.1.1)

I also have a Gemfile located in this directory which references the wdm gem.

Directory contents:

C:\MyR\knitr-jekyll>dir
 Volume in drive C has no label.
 Volume Serial Number is AC7D-A6A5

 Directory of C:\MyR\knitr-jekyll

06/23/2016  09:17 AM    <DIR>          .
06/23/2016  09:17 AM    <DIR>          ..
06/18/2016  07:59 PM                49 .gitignore
06/21/2016  07:49 PM             1,570 .Rhistory
06/21/2016  09:26 AM    <DIR>          .sass-cache
06/18/2016  07:59 PM               470 about.md
06/18/2016  07:59 PM             1,308 build.R
06/21/2016  09:26 AM    <DIR>          css
06/18/2016  07:59 PM             1,292 feed.xml
06/21/2016  09:28 AM    <DIR>          figure
06/23/2016  09:13 AM                44 Gemfile
06/18/2016  07:59 PM               506 index.html
06/18/2016  07:59 PM               300 knitr-jekyll.Rproj
06/18/2016  07:59 PM             1,077 LICENSE
06/18/2016  07:59 PM               979 README.md
06/21/2016  11:40 AM               625 _config.yml
06/21/2016  09:26 AM    <DIR>          _includes
06/21/2016  09:26 AM    <DIR>          _layouts
06/21/2016  09:26 AM    <DIR>          _posts
06/21/2016  09:26 AM    <DIR>          _sass
06/23/2016  09:19 AM    <DIR>          _site
06/21/2016  09:26 AM    <DIR>          _source
              11 File(s)          8,220 bytes
              11 Dir(s)  88,548,069,376 bytes free

Gemfile

gem 'wdm', '>= 0.1.0' if Gem.win_platform?

This edit is suggested at the Ruby documentation for listen, see http://www.rubydoc.info/gems/listen#On_Windows.

Thank you for your help. I'm hoping someone else may have run into this issue with Windows and maybe knows a workaround.

I really like the servr package even without the live updating feature working on Windows.

Periodic refresh

Apart from the rebuild after source changes, it would be cool if servr could also simply rebuild Rmds periodically after a configurable interval. This would enable use-cases such as daily reports without much cost/effort.

Authentication

Hello,
My understanding is that there is no way to open a server with a password. Would that be a feature you would consider adding ?
Maybe you know of an alternative package that allows to do this ?
Many thanks for all your cool work

jekyll 3.1.6 | Error: No such file or directory @ rb_sysopen

I have no idea whether it is more likely to be jekyll issue or jekyll on windows edition or yihui/servr itself but maybe you have faced this error message before and have somehow overworked it

> library(servr)
> servr::jekyll()
Configuration file: D:/MarcinKosinski.github.io/_config.yml
            Source: D:/MarcinKosinski.github.io
       Destination: D:/MarcinKosinski.github.io/_site
 Incremental build: disabled. Enable with --incremental
      Generating... 
jekyll 3.1.6 | Error:  No such file or directory @ rb_sysopen - /MarcinKosinski.github.io.Rproj
Error in jekyll_build() : Failed to run: jekyll build
In addition: Warning message:
running command 'jekyll build' had status 1 
> sessionInfo()
R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=Polish_Poland.1250  LC_CTYPE=Polish_Poland.1250   
[3] LC_MONETARY=Polish_Poland.1250 LC_NUMERIC=C                  
[5] LC_TIME=Polish_Poland.1250    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] servr_0.4

loaded via a namespace (and not attached):
[1] tools_3.3.1  Rcpp_0.12.5  httpuv_1.3.3

_config.yml

# Site settings

title: R Addict Blog #kosinski.r-addict.com # Title of your site
email: m.p.kosinski@gmail.com # Your contant email
name: "http://r-addict.com"

description: > # this means to ignore newlines until "baseurl:"
    I am an R addict with a biostatistical background, working in IT and keen on online recommendation. 
    I write about R Technologies, Survival Analysis and R Package Development.
baseurl: "" # the subpath of your site, e.g. /blog/
url: "http://r-addict.com" # the base hostname & protocol for your site
baseurlknitr: "/"

# Social links.
# Replace the word 'example' with your username if you want to include the icon in the left sidebar
# Delete the word 'example' if you don't want to include the icon in the left sidebar

twitter_username:     kosinski_rblog  # Replace this with your Twitter username
github_username:      MarcinKosinski  # Replace this with your GitHub username
linkedin_username:    marcin-kosiński-81435aab  # Replace this with your LinkedIn username
google_plus_username:  # 115677570336612137067  # Replace this with your Google+ username
facebook_username:    DataFortuneTelling  # Replace this with your Facebook username
dribbble_username:    # Replace this with your Dribbble username
stackoverflow_usernumber: 3857701 # stackoverflow user numer :) my own invention

# Build settings
markdown: kramdown
kramdown:
  input: GFM
  syntax_highlighter: rouge

highlighter: rouge


# Disqus comments:
disqus:           true
shortname:        r-addict

# Social Media
twitter:          true # add a twitter button to each post
facebook:         true # add a facebook share button to each post
linkedin:         true # my own button
googleplus:       true # my own button
facebooklike:     true # my own

author:
  name:           'Marcin Kosiński'
  email:          '[email protected]'

gems:
  - jekyll-feed  
  - rouge

# Permalinks
permalink: /:year/:month/:day/:title.html


github:
  repo:           https://github.com/MarcinKosinski/MarcinKosinski.github.io

PS. Thanks for this great package. I was able to create my blog with this package :)

Daemon mode breaks RSelenium's navigate() method

For animint, we've been using servr and RSelenium to test whether plots are rendered in the browser the way we expect. Plot rendering requires a file server, so before I discovered the new daemon support, I did something like:

library(servr)
library(RSelenium)
cmd <- "R -e \'cat(Sys.getpid(), file=\"pid.txt\"); servr::httd(dir=system.file(\"examples/make1\", package=\"servr\"), port=4848, browser=FALSE)\'"
system(cmd, wait = FALSE)
# start selenium server, open firefox, and navigate to file server on localhost
checkForServer(dir=system.file("bin", package = "RSelenium"))
startServer()
remDr <- remoteDriver(browserName = "firefox")
remDr$open(silent = TRUE)
remDr$navigate("http://localhost:4848/")
# kill the file server
tools::pskill(readLines("pid.txt", warn = F))

However, I run into problems if I use daemon=TRUE

res <- httd(dir = system.file("examples/make1", package = "servr"), 
            daemon = TRUE, port = 4848, browser = FALSE)
# The line below freezes firefox & the R session. However, it works if I _manually_ navigate there
# I can also use other methods like `remDr$getPageSource()`
remDr$navigate("http://localhost:4848/")

Any ideas why the daemon approach might cause this problem? Is there a somewhat simple explanation of the difference between the two approaches? Maybe @johndharrison could help? I don't think it's a browser issue as I've also tested this with phantomjs.

View server logs?

Is there some way to view server logs?

E.g.

writeLines("<h1>Hi</H1>", "index.html")
servr::httd()

# createTcpServer: address already in use
# To stop the server, run servr::daemon_stop(2) or restart your R session
# Serving the directory /Users/st/R/localhost at http://127.0.0.1:7826

If we now visit http://127.0.0.1:7826 through the browser we see the html as expected.

But in the R console we don't see any details about that request (e.g. HTTP method, user agent, IP etc). Could it be possible to display it (perhaps optionally, with something along the lines of servr::httd(verbose = T)

jekyll() needs custom baseurl on rstudio server

When trying to use jekyll() on RStudio Server, absolute paths relative to the base URL do not work.

When I run jekyll(), the site is served at "http://localhost:4321" and becomes (automagically) reachable at "http://my.rstudio.server/p/4321/". But since my _layouts/default.html, has <link rel="stylesheet" href="/assets/css/custom.css"/>, which is as it should be for hosting on GitHub pages (for example), the stylesheet cannot be found.

Somehow, the base url needs to include /p/4321/ on RStudio Server, right?

Display output when re-compiling R markdown?

It seems you've made a conscious decision to not display output when re-compiling R markdown. Would you be opposed to adding that option? I think it's helpful to see what's happening during interactive use and for debugging purposes (in fact, imo, that should be the default).

I'm already working on a PR, just want to make sure you agree...

encoding problem with Chinese

Hi, I'm trying to cluster text files written in Chinese.
tcm, and vocab were made with UTF-8.
However, plotting LDA model didn't work.
Does servr package provide work in UTF-8?
If it does, the problem would be in my codes....., I guess...
It would be very thankful if you see my codes and capture files.:

str(mylist)
image

it = itoken(mylist, ids = files.list, progressbar = FALSE)
v = create_vocabulary(it) %>% 
  prune_vocabulary(term_count_min = 10, doc_proportion_max = 0.2)
vectorizer = vocab_vectorizer(v)
dtm = create_dtm(it, vectorizer, type = "lda_c")

lda_model = 
  LDA$new(n_topics = 10, vocabulary = v, 
          doc_topic_prior = 0.1, topic_word_prior = 0.01)
doc_topic_distr = 
  lda_model$fit_transform(dtm, n_iter = 60, convergence_tol = 0.01, 
                          check_convergence_every_n = 10)

image

library(LDAvis)
library(servr)
lda_model$plot()

image

Unable to create rvest::html_session for servr::httd on Linux

I've cross-posted this issue on Stack Overflow.

On a Windows machine I am able to create a rvest::html_session to the server created by servr::httd(daemon = TRUE, browser = FALSE). That is:

# On Windows
servr::httd(daemon = TRUE, browser = FALSE, port = 4321) 
## Serving the directory /home/dewittpe/so/my-servr-question at http://127.0.0.1:4321
## To stop the server, run servr::daemon_stop("94019719908480") or restart your R session

R.utils::withTimeout(
                    {
                      s <- rvest::html_session("http://127.0.0.1:4321")
                    },
                    timeout = 3,
                    onTimeout = "error") 

s 
## <session> http://127.0.0.1:4321/
##   Status: 200
##   Type:   text/html
##   Size:   2352
servr::daemon_stop()

However, on my Linux box (Debian 9) I get the following

servr::httd(daemon = TRUE, browser = FALSE, port = 4321) 
## Serving the directory /home/dewittpe/so/my-servr-question at http://127.0.0.1:4321
## To stop the server, run servr::daemon_stop("94019719908480") or restart your R session

R.utils::withTimeout(
                    {
                      s <- rvest::html_session("http://127.0.0.1:4321")
                    },
                    timeout = 3,
                    onTimeout = "error") 
## Error: reached elapsed time limit
## Error in curl::curl_fetch_memory(url, handle = handle) :
##   Operation was aborted by an application callback

What can I do so that I can create an html_session based on a servr::httd
HTTP server within the same R session on Linux? I'm happy to provide additional detail on my R setup and machine set up as well.

installation error (Mutex creation failed) on manjaro/arch linux

install.packages('servr', repos = 'https://xran.yihui.name')  # devel version
Installing package into ‘/home/stephen/NOBACKUP/RLIB’
(as ‘lib’ is unspecified)
trying URL 'https://xran.yihui.name/src/contrib/servr_0.11.2.tar.gz'
Content type 'application/gzip' length 20692 bytes (20 KB)
==================================================
downloaded 20 KB

* installing *source* package ‘servr’ ...
** R
** inst
** byte-compile and prepare package for lazy loading
terminate called after throwing an instance of 'std::runtime_error'
  what():  Mutex creation failed
/usr/lib64/R/bin/INSTALL: line 34: 11429 Done                    echo 'tools:::.install_packages()'
     11430 Aborted                 (core dumped) | R_DEFAULT_PACKAGES= LC_COLLATE=C "${R_HOME}/bin/R" $myArgs --slave --args ${args}

The downloaded source packages are in
	‘/tmp/Rtmpc9duFK/downloaded_packages’
Warning message:
In install.packages("servr", repos = "https://xran.yihui.name") :
  installation of package ‘servr’ had non-zero exit status

This seems to a problem on arch linux (which Is what I'm using, or rather manjaro):

RcppCore/RcppParallel#77

and would indicate a short-term solution is to downgrade glibc, but is that the right thing for long-term?

URLs on RStudio Server

I know this isn't likely a "servr" issue, but I'm encountering it through servr::httd and I did not get any help from the rstudio community.

From RStudio Server, it used to be the case that a site launched through servr::httd(..., port = 1234) was available from my server session at "https://rstudio.example.org/p/1234". It's not anymore (since RStudio 1.2?); it's now at "https://rstudio.example.org/p/xyzpdq". Is there some way to control or at least capture that path through the "port" argument?

pass custom `--baseurl` argument to jekyll serve?

tl;dr The jeykll function cannot actually an argument for baseurl and pass it to servr_config because you have an argument of the same name in dynamic_site. Perhaps the latter argument could be renamed to avoid this conflict? (Or maybe you have a more clever solution).

The official Jekyll Documentation recommends using an empty string to --baseurl when previewing a site that is deployed on a gh-pages project repo (as opposed to a user/organization repo like username.github.io). With the appropriate configuration this makes it easy to preview the site locally and still deploy it automatically on gh-pages.

Looks like I should just be able to set baseurl="", but this results in an error: formal argument "baseurl" matched by multiple actual arguments since baseurl is also an argument to dynamic_site(). If I understand correctly, I only want to change the baseurl being used by server_config() and not that one being used by dynamic_site. Seems like renaming the argument as it is used in the latter case would do the trick?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.