Reputation: 815
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 ..!`)
Upvotes: 0
Views: 757
Reputation: 1371
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}`);
});
})
}
Upvotes: 1