簡體   English   中英

我運行了我的代碼並得到了這個錯誤:TypeError: eventType.toBuffer is not a function

[英]I ran my code and got this error: TypeError: eventType.toBuffer is not a function

當我嘗試在 Visual Studio 中運行以下代碼時,出現以下錯誤:

TypeError:eventType.toBuffer 不是 queueRandomMessage 中的函數

代碼:

    const Kafka = require('node-rdkafka');
    const eventType = require('../eventType.js');

    const stream = Kafka.Producer.createWriteStream({
      'metadata.broker.list': 'localhost:9092'
    }, {}, {
      topic: 'test'
    });

    stream.on('error', (err) => {
      console.error('Error in our kafka stream');
      console.error(err);
    });

    function queueRandomMessage() {
      const category = getRandomAnimal();
      const noise = getRandomNoise(category);
      const event = { category, noise };
      const success = stream.write(eventType.toBuffer(event));     
      if (success) {
        console.log(`message queued (${JSON.stringify(event)})`);
      } else {
        console.log('Too many messages in the queue already..');
      }
    }

    function getRandomAnimal() {
      const categories = ['CAT', 'DOG'];
      return categories[Math.floor(Math.random() * categories.length)];
    }

    function getRandomNoise(animal) {
      if (animal === 'CAT') {
        const noises = ['meow', 'purr'];
        return noises[Math.floor(Math.random() * noises.length)];
      } else if (animal === 'DOG') {
        const noises = ['bark', 'woof'];
        return noises[Math.floor(Math.random() * noises.length)];
      } else {
        return 'silence..';
      }
    }

    setInterval(() => {
      queueRandomMessage();
    }, 3000);

這是我使用的 eventType.js 的代碼:

const avro = require('avsc');

module.export = avro.Type.forSchema({
  type: 'record',
  fields: [
    {
      name: 'category',
      type: { type: 'enum', symbols: ['DOG', 'CAT'] }
    },
    {
      name: 'noise',
      type: 'string',
    }
  ]
});

我應該怎么做才能修復這個錯誤?

它應該是module.exports

const avro = require('avsc');

module.exports = avro.Type.forSchema({
  type: 'record',
  fields: [
    {
      name: 'category',
      type: { type: 'enum', symbols: ['DOG', 'CAT'] }
    },
    {
      name: 'noise',
      type: 'string',
    }
  ]
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM