serveStaticFiles: File-serving middleware

Description Usage Arguments Details Value Note Examples

View source: R/utils-middleware.R

Description

Binds to GET requests that aren't handled by specified paths. The result is to return files that are found on the host machine at the requested path. Binary file types like .png, .gif or .pdf are returned as raw bytes. All others are returned as characters.

Mime types are guessed using the mime package. The rawTypesPattern parameter is used to match mime types that should be returned as raw bytes.

Usage

1
2
3
4
5
6
7
serveStaticFiles(
  beakr = NULL,
  urlPath = NULL,
  rootPath = getwd(),
  rawTypesPattern = "image|json|octet|pdf|video",
  verbose = FALSE
)

Arguments

beakr

Beakr instance or NULL.

urlPath

String representing the URL directory underneath which static file paths will appear.

rootPath

String representing the absolute path used as the root directory when searching for files on host machine. Defaults to the directory in which the script is running.

rawTypesPattern

String pattern identifying mime types to be returned as raw bytes.

verbose

Boolean to show a verbose static file information.

Details

All files to be served in this manner must exist underneath the host machine directory specified with rootPath. The directory structure underneath rootPath will be mapped onto URLs underneath urlPath. This helps when deploying web services at preordained URLs.

The example below presents files underneath host machine directory hostDir/ to be accessed at URLS under test/.

Value

A Beakr instance with added middleware.

Note

If you run the example in the console, be sure to stopServer(bekar) when you are done.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
library(beakr)

# Create a .txt file in temp directory
hostDir <- tempdir()
file <- paste0(hostDir, "/my_file.txt")
cat("I am a text file.", file = file)

# Create an new beakr instance
beakr <- newBeakr()

# beakr pipeline
beakr %>%

  # Respond to GET requests at the "/hi" route
  httpGET(path = "/hi", function(req, res, err) {
    print("Hello, World!")
  }) %>%

  # Respond to GET requests at the "/bye" route
  httpGET(path = "/bye", function(req, res, err) {
    print("Farewell, my friends.")
  }) %>%

 # Host the directory of static files
 serveStaticFiles("/test", hostDir, verbose = TRUE) %>%

 # Start the server on port 25118
 listen(host = "127.0.0.1", port = 25118, daemon = TRUE)

# ------------------------------------------------------------
# POINT YOUR BROWSER AT:
# * http://127.0.0.1:25118/test/my_file.txt
#
# THEN, STOP THE SERVER WITH stopServer(beakr)
# ------------------------------------------------------------

# Stop the beakr instance server
stopServer(beakr)

beakr documentation built on April 7, 2021, 1:06 a.m.