簡體   English   中英

從 node.js 調用 shell 腳本

[英]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 腳本(例如作為使用模板的字符串等),執行它(使用execspawn ?),然后讀取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 RscriptR命令,並通過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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM