![](/img/trans.png)
[英]Node.js passport.use() function: TypeError: Cannot read properties of undefined (reading 'use')
[英]Node.JS IPFS sending message TypeError: Cannot read properties of undefined (reading 'publish')
我正在嘗試通過 IPFS.network 發送消息,但我不斷收到錯誤TypeError: Cannot read properties of undefined (reading 'publish')
。
錯誤發生在node.pubsub.publish(topic, msg, (err) => {})
行。
ipfs.js
是應用程序的主要引擎,包含與 IPFS.network 交互所需的方法。
'sendNewMsg' 方法用於將消息發送到主題,其他節點可以在該主題中訂閱和閱讀消息。
index.js
調用並執行該方法。
你能幫我發現並解決問題嗎?
提前致謝!
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};
索引.js:
const {IPFSEngine} = require('./ipfs');
const ipfs = new IPFSEngine();
ipfs.sendNewMsg(`topic2`,`Messages 2 ..!`)
當您嘗試訪問 object 上的publish
屬性時,錯誤指出node.pubsub
未定義。
快速閱讀IPFS 文檔中的一個示例, IPFS.create
似乎是一個異步的 API,結果您沒有等待。 它可以解釋為什么您在節點上獲得未定義的pubsub
屬性。
使用異步 function,你可以這樣寫:
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}`);
});
}
或者沒有 async/await 語法:
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}`);
});
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.