简体   繁体   中英

Calling R script from node.js issue loading libraries

I am using 'r-script' npm package to run a R script from node.js. This R script calls another R script which loads a lot of libraries. I get an error 'there is no package 'zoo'' in the backend. I have R version 3.5.3 and when I run these R files from RStudio, it runs seemlessly. I have correctly defined PATH variable in environment setting. I am using React for frontend.

I have tried running the app from command line as administrator but it still gives the same error.

//Backend

//server.js
router.post("/putData", (req, res) => {

    const {simid,delay,decay} = req.body;

    let rout = R('rscript.R')
                .data()
                .callSync();
    console.log(simid + delay + decay);
    console.log(rout);
    return res.json({success:true});

  });

//rscript.R

#rscript.R
    source("Main.R")

//Main.R

#Main.R
require(zoo)
require(quantmod)
require(Rcpp)
(And a lot of other libraries)

I recieve the following error at the server end:

[0] POST /api/putData 500 12314.741 ms - 578 /n
[0] Loading required package: zoo
[0] Loading required package: quantmod
[0] Loading required package: xtable
[0] Loading required package: tidyr
[0] Loading required package: hashmap
[0] Loading required package: Quandl
[0] Loading required package: Rcpp
[0] Loading required package: readr
[0] Loading required package: roll
[0] Loading required package: gridExtra
[0] Error in R script rscript.R
[0]  'there is no package called 'zoo''

I found the solution. As mentioned in the documentation of 'r-script' npm package on github, you should use needs() instead of library() or require() for loading a package. So I installed 'needs' package from RStudio. After installtion, it gave a prompt that would you like to automatically load this package whenever a function from it is called. You won't be able to successfully respond from here as you will need write permission. So open command prompt as administrator, load R by typing (R), and then run library(needs). Now you get a prompt again, choose Yes and you are done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM