'How can I activate a '.js' script from R?

I have a '.js' script that I usually activate from the terminal using the command node script.js. As this is part of a process where I first do some data analysis in R, I want to avoid the manual step of opening the terminal and typing the command by simply having R do it for me. My goal would be something like this:

...R analysis
write.csv(df, "data.csv")
system('node script.js')

However, when I use that specific code, I get the error:

sh: 1: node: not found
Warning message:
In system("node script.js") : error in running command

Of course, the same command runs without problem if I type it directly on the terminal.

About my Software

I am using:

  • Linux computer with the PopOS!
  • RStudio 2021.09.1+372 "Ghost Orchid"
  • R version 4.0.4.


Solution 1:[1]

The error message node: not found indicates that it couldn't find the program node. It's likely in PATH in your terminal's shell, but not in system()'s shell (sh).

In your terminal, locate node by executing which node. This will show the full path to the executable. Use that full path in system() instead.

Alternatively, run echo $PATH in your terminal, and run system('echo $PATH') or Sys.getenv('PATH') in R. Add any missing directories to R's path with Sys.setenv(PATH = <your new path string>)

Note that system2() is recommended over system() nowadays - but for reasons unimportant for your case. See ?system and ?system2 for a comparison.

Examples

Terminal

$ which node
/usr/bin/node

R

system('/usr/bin/node script.js')
# alternatively:
system2('/usr/bin/node', c('script.js'))

or adapt your PATH permanently:

Terminal

% echo $PATH
/usr/local/bin:/home/caspar/programs:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin

R

> Sys.getenv('PATH')
[1] "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/Applications/RStudio.app/Contents/MacOS/postback"

> Sys.setenv(PATH = "/home/caspar/programs:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/Applications/RStudio.app/Contents/MacOS/postback")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Caspar V.