簡體   English   中英

如何顯示從Node JS服務器到客戶端的Shell腳本結果?

[英]How to display result of shell script from node js server to the client?

我有一個節點js服務器,它觸發了我擁有的shell腳本。 代碼如下(簡單的Hello World示例):

var http = require("http");    

function onRequest(request, response) {
    console.log("Request received.");
    response.writeHead(200, {"Content-Type": "text/plain"});

    var spawn = require('child_process').spawn;
    //executes my shell script - main.sh when a request is posted to the server
    var deploySh = spawn('sh', [ 'main.sh' ]);
    //This lines enables the script to output to the terminal
    deploySh.stdout.pipe(process.stdout);

    //Simple response to user whenever localhost:8888 is accessed
    response.write("Hello World");
    response.end();
}

http.createServer(onRequest).listen(8888);
console.log("Server has started.");

代碼完美運行-啟動服務器,每當在瀏覽器中加載頁面(請求)時,shell腳本就會在服務器上運行,並在終端上輸出結果。

現在,我想將該結果顯示回客戶端瀏覽器,而不僅僅是“ Hello World”。 怎么做? 請注意,腳本需要4到5秒鍾來執行並生成結果。

您有兩種選擇:

選項1:

將函數轉換為使用child_process.exec方法而不是child_process.spawn方法。 這將把所有發送到stdout數據緩沖在內存中,並允許您跨行作為一個塊發送到瀏覽器:

var http = require("http"),
    exec = require("child_process").exec;

function onRequest(request, response) {
  console.log("Request received.");
  response.writeHead(200, {"Content-Type": "text/plain"});

  //executes my shell script - main.sh when a request is posted to the server
  exec('sh main.sh', function (err, stdout, stderr) {
    if (err) handleError();

    //Print stdout/stderr to console
    console.log(stdout);
    console.log(stderr);

    //Simple response to user whenever localhost:8888 is accessed
    response.write(stdout);
    response.end();
  });
}

http.createServer(onRequest).listen(8888, function () {
  console.log("Server has started.");
});

選項2:

如果要保留child_process.spawn方法,則需要在堆棧中引入實時網絡,以便在從子進程接收事件時將數據事件推送到瀏覽器。 查看socket.io或(推薦)SockJS,以在服務器和客戶端之間建立實時通信。

邊注:

我想指出上面的代碼中的一個缺陷,從長遠來看,這最終會傷害到您將來對節點的努力。

function onRequest(request, response) {
  console.log("Request received.");
  response.writeHead(200, {"Content-Type": "text/plain"});

  var spawn = require('child_process').spawn;

在上面的最后一行中,您需要在每個請求上使用child_process模塊。 這不僅會給每個請求增加不必要的開銷,而且如果您不小心的話,最終會遇到模塊緩存問題。 建議所有對require的調用都發生在模塊作用域的頂部,而不是其他地方。 只有在構建真正的同步CLI工具時,它的“可接受”調用邏輯中的唯一一次了–但是即使如此,最好還是將所有需求組織在模塊范圍的頂部,以提高可讀性。

 var http = require('http'),
 process = require('child_process');


var server =  http.createServer(function (req,res){

    res.writeHead(200,{'content-type':'text/html'});
        process.exec('ls',function (err,stdout,stderr) {
            if(err){
                console.log("\n"+stderr);
                res.end(stderr);
            } else {
                    console.log(stdout);
                    res.end("<b>ls displayes files in your directory</b></br>"+stdout+"</br>"); 
                }
            }); 

 }).listen(3000);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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