[英]How do I check if a node.js process is being piped input from stdout?
我目前正在構建一個接受來自python腳本的輸入的節點應用程序。 我們計划做這樣的管道,例如pyton script.py | node index.js
pyton script.py | node index.js
。
我想檢查是否有輸入正在傳遞。這樣,如果有數據正在傳遞,請啟動快速服務器。 但是,如果沒有管道傳輸的數據,則退出節點進程。 我目前正在檢查流中的輸入,但是我意識到,如果沒有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}`);
});
});
我建議您使用get-stdin
模塊( https://github.com/sindresorhus/get-stdin )。 基於promises
,它具有更好的界面。 您可以從stdin
獲取結果,然后啟動快速服務器。
getStdin().then(key => {
if(key === ""){
console.log("KEY UNDEFINED");
process.exit(1);
}
app.listen(PORT, () => {
console.log(`Application started on port:${PORT}`);
});
});
我建議您可以使用一個有趣的npm軟件包之一,名為“ python-shell”及其功能,如下所示:
這是一個簡單的示例:
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
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.