2017-06-21 22 views
0

我目前正在構建一個接受來自python腳本的輸入的節點應用程序。我們打算做這樣的管道pyton script.py | node index.js如何檢查node.js進程是否從stdout進行管道輸入?

我想檢查是否有輸入輸入。這樣,如果有數據正在輸送,請啓動快速服務器。但是,如果沒有管道數據退出節點進程。我目前正在檢查流的輸入,但我意識到如果沒有來自stdout的輸入,我無法做到這一點。有誰知道更好的解決方案?

這是我到目前爲止。

import app from "./app"; 
import { PORT } from "./config"; 

process.stdin.setEncoding("utf8"); 

let key = ""; 
process.stdin.on("data", data => { 
    key += data; 
}); 

process.stdin.on("end",() => { 
    global.key = key; 
    if(global.key === ""){ 
    console.log("KEY UNDEFINED"); 
    process.exit(1); 
    } 
    app.listen(PORT,() => { 
    console.log(`Application started on port:${PORT}`); 
    }); 
}); 

回答

0

我建議你用get-stdin模塊(https://github.com/sindresorhus/get-stdin)去。它具有更好的界面,基於promises。你可以從stdin得到結果,然後啓動你的express服務器。

getStdin().then(key => { 
    if(key === ""){ 
     console.log("KEY UNDEFINED"); 
     process.exit(1); 
    } 
    app.listen(PORT,() => { 
     console.log(`Application started on port:${PORT}`); 
    }); 
}); 
0

我建議你可以使用一個名爲「蟒蛇殼」有趣的NPM包,其功能之一爲:

  1. 在一個子進程
  2. 內置可靠產卵Python腳本文本,JSON和二進制模式
  3. 定製解析器和格式化通過stdin和stdout
  4. 簡單和高效的數據傳輸流
  5. 引發錯誤時的擴展堆棧跟蹤。

,這裏是一個簡單的例子:

var PythonShell = require('python-shell'); 

PythonShell.run('script.py', function (err,results) { 
    //Results : array of messages collected during execution. 
    if(err){ 
    //Error handling 
    } 
    else if(results.length > 0){ 
    //Start the server 
    } 
}); 
相關問題