IPFS.swarm.peers gives empty array

I have a function like this:

`async getIpfsPeers() {
    const peers = await this.node.swarm.peers();
    console.log("List of connected peers: ", peers);
    return peers;
}`

It’s inside a class, the class factory function is creating the IPFS instance. Bootstrap list works.

This is the output:
List of connected peers: []

Why am I seeing empty array?

Are you doing this shortly after the instance is created? Is it possible that the node just hasn’t had a chance to connect to any peers yet?

2 Likes

Yes, that indeed helped. Thank you!

You’ll also need to make sure, you have the right peers or a certain amount connected, otherwise you’ll be connected but the intended party won’t be able to get your content or receive your messages.

In https://github.com/QuestNetwork/qDesk/blob/master/src/app/sign-in/sign-in.component.ts we have:

 while(!this.q.os.isReady()){
        console.log('SignIn: Waiting for Quest OS...');
        this.q.os.sendBootMessage('Waiting For Peers... '+this.end()+'s');
        await this.ui.delay(5000);
      }

which allows to make sure all the conditions critical to the successful execution of methods like swarm.peers() are met

1 Like

If you’re running an IPFS node in the same process you can also listen for peer:connect events fired by libp2p’s connection manager:

const IPFS = require('ipfs')

const ipfs = await IPFS.create()

ipfs.libp2p.connectionManager.on('peer:connect', (peerId) => {
  console.info('peer:connect', peerId.toString())
})

If it’s a remote node accessed via the ipfs-http-client, you have to poll the ipfs.swarm.peers method:

const waitFor = require('p-wait-for')

await waitFor(async () => Boolean((await ipfs.swarm.peers()).length))
2 Likes