2016-12-03 70 views
0

我有一個控制檯 在硬件連接,但它的工作與命令:如何在NodeJS中執行shell腳本並等待它顯示並進入流?

enter image description here

創建omron.sh,因爲我需要在的NodeJS

#!/bin/sh 

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/splincode/Develop/omron/c++_modules/libomron/omron-build/lib/ 
~/Develop/omron/usr/local/bin/omron_790IT_test 

運行它,但我需要它在NodeJS中工作並寫入流標準輸出,但不起作用

server.js:

let http = require('http'), 
    fs = require('fs'), 
    url = require('url'), 
    path = require('path'); 

let server = new http.Server(); // EventEmitter 

server.listen(8000, '127.0.0.1'); 
server.on("connection",() => console.log("connection")); 
server.on('request', (request, response) => { 

    console.log('.', request.url) 

    let userUrl = decodeURIComponent(url.parse(request.url).pathname); 
    let loadFile = false; 

    switch(userUrl) { 
     case '/': 
      userUrl += 'index.html'; 
      loadFile = true; 
     break; 

     case '/omron': 

      console.log('omron') 

      var util=require('util') 
      var exec=require('child_process').spawn('sh', ['omron.sh']); 

      // not work 
      exec.stdout.on('data', (data) => { 
       console.log(`stdout: ${data}`); 
       response.end(`${data}`); 
      }); 

     break; 

     default: 
      loadFile = true; 
     break; 
    }; 


    if (userUrl === '/') userUrl += 'index.html'; 


    if (loadFile) { 
     let pathname = path.normalize(path.join(__dirname, userUrl)); 
     fs.readFile(pathname, (err, content) => { 
      let mime = require('mime').lookup(pathname); 
      response.setHeader('Content-Type', `${mime}; charset=utf-8`); 
      response.end(content); 
     }); 
    } 


}); 

但是,沒有工作,我需要給shell腳本一個輸出流的響應,但是如何?

enter image description here

+0

ü可以嘗試節點-CMD模塊 – Adiii

+0

完美,非常感謝的! – splincode

+0

我可以發表我的評論作爲接受答案嗎? – Adiii

回答

1

節點-CMD

Simple commandline/terminal interface to allow you to run cli or 
    bash style commands as if you were in the terminal. 

運行異步命令,並且如果需要可以得到輸出爲字符串。

所以做一些這樣的事來解決問題

var cmd=require('node-cmd'); 

cmd.get(
    'pwd', 
    function(data){ 
     console.log('the current working dir is : ',data) 
    } 
); 

cmd.run('whoami'); 
相關問題