ch-03/hello-pkgs/pacakge.json
{
"name": "hello-pkgs",
"version": "0.1.0",
"description": "basic node and webr cli example that uses other packages",
"main": "index.mjs",
"type": "module",
"dependencies": {
"webr": "^0.2.2"
}
}Base R installs come with many goodies, but one aspect of R that makes it so useful is the vast ecosystem of packages that extend the core functionality.
As of the timestamp on the book, WebR has successfully built nearly half of the packages on CRAN, so there’s a decent chance what you need is available.
Let’s see how to naively use the same idioms that the actual web-version of WebR uses to incorporate packages into web-based JavaScript programs.
We’ll keep this chapter simple and use the {cowsay} package to output some text to the console.
I made a copy of the hellow-webr directory as hello-pkgs and modified the package.json accordingly:
ch-03/hello-pkgs/pacakge.json
{
"name": "hello-pkgs",
"version": "0.1.0",
"description": "basic node and webr cli example that uses other packages",
"main": "index.mjs",
"type": "module",
"dependencies": {
"webr": "^0.2.2"
}
}Similary, index.mjs now looks like the following (only new features have annotations):
ch-04/hello-pkgs/index.mjs
Here’s the output of that on one of my systems:
$ time node index.mjs
--------------
Hello from WebR + Node!
--------------
\
\
\
|\___/|
==) ^Y^ (==
\ ^ /
)=*=(
/ \
| |
/| | | |\
\| | |_|/\
jgs //_// ___/
\_)
node index.mjs 2.85s user 1.06s system 151% cpu 2.580 totalThat took a bit more time than the example in the previous chapter! This is due to WebR needing to download the {cowsay} package from the internet each time we run the program. This is super inefficient and quite unnecessary, so we’ll avoid getting you used to this bad practice and see how to improve upon it in the next chapter.
Before moving on:
quiet: false in the call to installPackagescowsay::say()’s by parameter.Give Installing R Packages at least a skim before continuing so you can fully appreciate the differences between what we will be doing and what we just did.
In the next chapter we’ll cover how to store all those dependent packages on the local filesystem and use them with WebR in Node.