在Node.js和Express中调用R脚本报错:Cannot read property 'data' of undefined
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-scriptis installed: Runnpm install r-scriptif you haven't already. - Verify your R environment is set up: Make sure you can run
Rin your terminal, and thattest.Routputs something (useprint()at the end of the script so r-script can capture it). - Confirm file permissions: Ensure your Node app has read access to the
scriptsfolder andtest.Rfile.
内容的提问来源于stack exchange,提问作者mvs

