I thought gun instance in the server was also one of the peers. But when I put data on the server, the peer can't get the data.
Here is my simple test code.
global.gun.get('servertest').put('yes'); // at server side
gun.get('servertest').once(console.log); // at client side
And it prints undefined. please, let me know how to use a gun instance on server side.
On the server, run this to actually accept remote connections:
On the client, run this to connect to your server:
As a side note, even if you establish a peer connection to get your data, you still need to handle
undefined, asonce()might fire several times as data is coming in.Relevant links:
EDIT: To be more explicit about my side note above -- the
oncecallback on your client gettingundefinedfor non-local data is actually by design. It means the client does not have the requested data available yet. It will however request it from its peers, which will try to answer with what they themselves can resolve (locally or from their respective peers). These answers will trigger the callback again (if they got through the CRDT algorithm I think).Getting
undefinedon the client could also mean the server's response might have timed out and GUN considered it unanswered. You can prolong the waiting time with.once(callback_function, {wait: time_in_miliseconds}).As per Hadar's answer, try using
on()instead ofonce()to mitigate race conditions, i.e. your client requesting data from the server before you actually wrote it. Once you got your data and don't want any more updates, you can unsubscribe withgun.get('servertest').off()Also, it might be noteworthy that GUN instances are not magically linked; having two of them connected does not mean they are one and the same in any way. Conceptually, they are peers in a distributed system, which in GUN's case gives you eventual consistency with all the limits and tradeoffs associated with that.