从node.js调用shell脚本
我怎样才能在Node.js中生成一个脚本和pipe道到壳?
例如我可以创build这个文件,例如hello.R
,使其可执行chmod +x hello.R
并从命令行运行./hello.R
:
#!/usr/bin/Rscript hello <- function( name ) { return (sprintf( "Hello, %s", name ); }) cat(hello("World"));
我想要做的是做Node的等价物。 特别是在内存中生成一个更复杂的R脚本(例如,使用模板等string),执行它(使用exec
或spawn
?),并读取stdout
。
但我不能完全弄清楚如何pipe脚本R.我尝试了(除其他外):
var rscript = [ hello <- function( name ) { return (sprintf( "Hello, %s", name ); }) cat(hello("World")); ].join('\n'); var exec = require('child_process').exec; exec(rscript, { shell: '/usr/bin/R'}, function(err, stdout, stderr) { if (err) throw(err); console.log(stdout); });
但是,由于它看起来既不是/usr/bin/R
也不是/usr/bin/Rscript
了解-c
开关:
检查child_process的nodejs文档。 您应该能够像在terminal上一样spawn
Rscript
或R
命令,并通过child.stdin
发送命令。
var c = require('child_process'); var r = c.spawn("R",""); r.stdin.write(rscript); /* now you should be able to read the results from r.stdout a/o r.stderr */