[英]call shell script from node.js
如何在 Node.js 中生成腳本並通過管道傳輸到 shell?
例如,我可以創建這個文件,例如hello.R
,使其可執行chmod +x hello.R
並從命令行運行它, ./hello.R
:
#!/usr/bin/Rscript
hello <- function( name ) { return (sprintf( "Hello, %s", name ); })
cat(hello("World"));
我想做的是從 Node.js 做等效的事情。 特別是在內存中生成一個更復雜的 R 腳本(例如作為使用模板的字符串等),執行它(使用exec
或spawn
?),然后讀取stdout
。
但我不太清楚如何將腳本通過管道傳輸到 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
開關:
檢查的文檔的NodeJS child_process 。 您應該能夠像在終端上一樣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 */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.