2
0

client.js 943 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const http = require("http");
  2. const https = require("https");
  3. class PyPubSub {
  4. constructor(url) {
  5. this.url = url;
  6. this.getter = url.match(/^https/i) ? https : http;
  7. }
  8. attach(func) {
  9. this.getter.get(this.url, res => {
  10. res.setEncoding("utf8");
  11. let body = '';
  12. res.on("data", data => {
  13. body += data;
  14. if (data.endsWith("\n")) {
  15. let payload = JSON.parse(body);
  16. body = '';
  17. func(payload);
  18. }
  19. });
  20. });
  21. }
  22. }
  23. // Test
  24. function process(payload) {
  25. // ping-back?
  26. if (payload.stillalive) {
  27. console.log("Got a ping-back");
  28. // Actual payload? process it!
  29. } else {
  30. console.log("Got a payload from PyPubSub!");
  31. console.log(payload);
  32. }
  33. }
  34. const pps = new PyPubSub('http://localhost:2069/');
  35. pps.attach(process);