Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

246
Visualizações
Node.JS IPFS sending message TypeError: Cannot read properties of undefined (reading 'publish')

I'm trying to send a message through an IPFS network but I keep getting the error TypeError: Cannot read properties of undefined (reading 'publish').

The error occurs at line node.pubsub.publish(topic, msg, (err) => {}).

ipfs.js is the app's main engine and contains the methods needed to interact with the IPFS network.

The 'sendNewMsg' method is used to send messages to a topic where other peers can subscribe and read the messages.

index.js calls and executes the method.

Could you please help me spot and fix the problem?

Thanks in advance!

ipfs.js:


const IPFS = require('ipfs');
const BufferPackage = require('buffer');

const Buffer = BufferPackage.Buffer;

class IPFSEngine {

    constructor(){
        let node = IPFS.create({
            EXPERIMENTAL: { pubsub: true },
            repo: (() => `repo-${Math.random()}`)(),
            config: {
                Addresses: {
                    Swarm: [
                        '/dns4/ws-star.discovery.libp2p.io/tcp/443/wss/p2p-websocket-star'
                    ]
                }
            }
        });

        this.node = node;
    }

    ....
    ....
    ....

    sendNewMsg(topic, newMsg) {
        let {node} = this;
        console.log('Message sent: ', newMsg)
        const msg = Buffer.from(newMsg)
        node.pubsub.publish(topic, msg, (err) => {
            if (err) {
                return console.error(`Failed to publish to ${topic}`, err)
            }
            // msg was broadcasted
            console.log(`Published to ${topic}`)
        })
    }
}

// Export IPFSEngine
module.exports = {IPFSEngine};

index.js:


const {IPFSEngine} = require('./ipfs');

const ipfs = new IPFSEngine();

ipfs.sendNewMsg(`topic2`,`Messages 2 ..!`)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The error states that node.pubsub is undefined while you are trying to access the publish property on the object.

Quickly reading through an example from the IPFS documentation, it appears that IPFS.create is an asynchronous API, which result you are not awaiting. It could explain why you get an undefined pubsub property on your node.

Using an async function, you could write something like:

async function sendNewMsg(topic, newMsg) {
  let { node } = this;
  console.log('Message sent: ', newMsg);
  const msg = Buffer.from(newMsg);
  (await node).pubsub.publish(topic, msg, (err) => {
    if (err) {
      return console.error(`Failed to publish to ${topic}`, err);
    }
    // msg was broadcasted
    console.log(`Published to ${topic}`);
  });
}

Or without the async/await syntax:

function sendNewMsg2(topic, newMsg) {
  let { node } = this;
  console.log('Message sent: ', newMsg);
  const msg = Buffer.from(newMsg);
  node.then((readyNode) => {
    readyNode.pubsub.publish(topic, msg, (err) => {
      if (err) {
        return console.error(`Failed to publish to ${topic}`, err);
      }
      // msg was broadcasted
      console.log(`Published to ${topic}`);
    });
  })
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda