Provides a method to call R Script in Nodejs. The Node framework I use is EggJS, and the sample code is all implemented in Egg. You’ll see some of the previous aspects.

  • Introduction to R and why R Script is called in Node
  • Related environment construction and key Node knowledge
  • Call method and related code

Introduction to R and why R Script is called in Node

R is the language and operating environment for statistical analysis and mapping. R is a free, free, open source software for the GNU system. It is an excellent tool for statistical calculation and statistical mapping. Simply put, anyone who is supposed to do this knows the background.

R Script needs to be called in a Node call because the application needs to translate complex calculation formulas involving trigonometry, square root, or idempotent math. However, when translating directly with Javascript, the whole calculation result will be abnormal due to the accuracy problem in the calculation process. For example, math. tan is 0.000000000000001 and so on.

When you search for similar packages, you will see r-script, Node-rscript, JS-Cal-r, and Rscript. They must have written something that works. If you have a Json array with a length of 10,000, or if your R Script runs in R Studio and is called in Node as usual, you will get an error, or even if you use the sample code on the Packeage page. In short, the situation can be very complicated.

2. Related environment construction and key Node knowledge

2.1 Related environment construction

First of all, the machine must need to build the Node environment and R environment, Node environment will not be introduced. If you happen to use Eggjs, please check out the website.

For R environments, you only need to install the latest R package. The latest version is R Version 3.5.1. The official website is at the following location on the official website.

After the installation needs to configure the system environment variables, mobile to configure. This step is very important. Add the bin and include paths to the system variable Path in the system convenience. According to my installation Path, I installed it on disk C, so the Path is as follows

C: \ Program Files \ R \ R - 3.5.1 track of \ bin C: \ Program Files \ R \ R - 3.5.1 track of \ the includeCopy the code

2.2 Nodejs knowledge points

In fact, there is only one way to call R script in Node and that is to execute R script from the command line. I took a cursory look at the source code of the Package mentioned earlier. Very lax conclusion, their implementation idea is actually the same, the difference is in the parameter processing, has returned the value of the processing.

R Script command line execution scripts look like this

Rscript R_File_Path Parameter Data pair path of the R_File_Path:.R file Parameter: The Parameter type is a stringCopy the code

So the key question “Node calls R Script “becomes how to” run the command line in Node “. The solution to this problem is to call exec in the child_process of the Node module

var child_process = require('child_process');
var exec = child_process.exec;
Copy the code

So what child_process is, I’m not going to expand it here, or I’m going to blur the point. Because many times, I read other people’s articles, the author is very kind to list the relevant knowledge points, very detailed, very carefully. But for a toolpusher like me, it takes too long, and it blurs the focus. I want to solve my problem right now. For code reference, please see the official website for details.

Call method and related code

So, the code is provided directly below. The code is an example, and is not very formal; for example, operations that retrieve data from an egg are better placed inside a service.

'use strict';

const path = require("path")
const child_process = require('child_process');
const exec = child_process.exec;

const Controller = require('egg').Controller;

class TestRController extends Controller {
  async echo() {
    let Parameter = path.join(__dirname, ". /.. /public/assets/csv/tilt.csv");
    let R_File_Path = path.join(__dirname, ". /.. /public/assets/r/tilt.R");
    let cmd = 'Rscript' + '"' + R_File_Path + '"' + Parameter;
    
    exec(cmd, (error, stdout, stderr) => {
        if (error) {
            consle.log(stderr);
        } else{ console.log(stdout); }}); } } module.exports = TestRController;Copy the code

One of the more important callback results of exec method, what each parameter means, see the above figure needs to explain or the official website. Explain the trick of passing parameters if the result is returned after execution. If the amount of data is small, put it in the parameters

'Rscript R_File_Path "{a:1,b:'p1'} ";Copy the code

This way R Script can accept the argument string directly, and can also be serialized to JSON for further processing.

However, when the parameters are too large, passing them directly can cause problems. The technique to deal with a large number of data parameters is to store the parameter data in.txt,.json,.csv files, directly pass the absolute path of the parameter file R Script to complete the processing. Similarly, when data is returned, there will also be a limit on the amount of data. If the amount of data is small, it can be directly returned as JSON string; if it is too large, it will be saved as a file by R and the absolute path will be returned.

There are two other points worth sharing

  1. How do I get parameters in R Script
args <- commandArgs(trailingOnly = TRUE)
Copy the code
  1. Exec method parameters are correct in Nodejs, and the code is well sproutedcmdCommand incmd.exeIt can be executed normally. When executed in Node, the Pakckage used in R Script is not installed. And the error is repeated no matter how many times you reload in R Studio. Solutions:

Check the library path, such as C: Program Files\R\ r-3.5.1 \library for such a Package. If not, download the referenced Package and then manually copy it to this path.

This is how I solved the problem of Nodejs calling R script in Nodejs.

— — — — — — — —

I’ll be happy to write a technical article for the first time if it helps you. If you see anything that can be improved, please give me some advice. I hope I can stick to it and share more of my knowledge in the future.