You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Node.js和Express中调用R脚本报错:Cannot read property 'data' of undefined

Fixing "Cannot read property 'data' of undefined" When Calling R Scripts in Express with r-script

Hey there, let's break down why you're hitting this error and how to fix it quickly.

The Root Cause

That error pops up because the path you're passing to r-script is wrong—so it can't find your test.R file, returns undefined, and then you try to call .data() on nothing.

Looking at your project structure:

--routes
  ----index.js
  ----graph.js
--scripts
  ----test.R
--server.js

When you write R("./scripts/test.R") inside routes/graph.js, Node looks for the script at routes/scripts/test.R (since ./ is relative to the current file's folder). But your actual script lives in the project root's scripts folder, so that path doesn't exist.

Quick Fixes

1. Use a Relative Path That Jumps Up a Level

Update the path to go one directory up from routes to the root, then into scripts:

router.get('/test', function(req, res, next) { 
  var R = require("r-script"); 
  var out = R("../scripts/test.R")
    .data()
    .callSync(); 
  res.send(out); 
});

2. Use an Absolute Path (More Reliable)

For a foolproof solution, use Node's __dirname and the path module to build an absolute path. This works no matter how your file structure changes later:

const path = require('path'); // Don't forget to import path!

router.get('/test', function(req, res, next) { 
  var R = require("r-script"); 
  // Build the full path to your R script
  const scriptPath = path.join(__dirname, '../scripts/test.R');
  var out = R(scriptPath)
    .data()
    .callSync(); 
  res.send(out); 
});

Extra Checks to Make Sure It Works

  • Double-check that r-script is installed: Run npm install r-script if you haven't already.
  • Verify your R environment is set up: Make sure you can run R in your terminal, and that test.R outputs something (use print() at the end of the script so r-script can capture it).
  • Confirm file permissions: Ensure your Node app has read access to the scripts folder and test.R file.

内容的提问来源于stack exchange,提问作者mvs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:05:14