receive_generator.js 989 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/env node
  2. 'use strict';
  3. const co = require('co');
  4. const amqp = require('amqplib');
  5. const readline = require('readline');
  6. co(function* () {
  7. const myConsumer = (msg) => {
  8. if (msg !== null) {
  9. console.log('consuming message %s in generator', JSON.stringify(msg.content.toString()));
  10. }
  11. };
  12. const conn = yield amqp.connect('amqp://localhost');
  13. try {
  14. // create a message to consume
  15. const q = 'hello';
  16. const msg = 'Hello World!';
  17. const channel = yield conn.createChannel();
  18. yield channel.assertQueue(q);
  19. channel.sendToQueue(q, Buffer.from(msg));
  20. console.log(" [x] Sent '%s'", msg);
  21. // consume the message
  22. yield channel.consume(q, myConsumer, { noAck: true });
  23. }
  24. catch (e) {
  25. throw e;
  26. }
  27. }).catch(err => {
  28. console.warn('Error:', err);
  29. });
  30. const rl = readline.createInterface({
  31. input: process.stdin,
  32. output: process.stdout
  33. });
  34. // pend until message is consumed
  35. rl.question('newline to exit', () => process.exit());