In node.js event is not fired

by xiaofo   Last Updated June 13, 2019 05:28 AM

I am using web socket to get event. sending transaction works fine. but event is not fired.

also I referred Web3 events not working

but it does not work, too.

I used eventemitter also. but it did not work, too. I think there is a problem '.on'. Is there any similar case to me ?

My solidity code is:

event MyEvent(...);

function MyFunction(...) public {
   ...
   emit MyEvent(...);
}

My node.js code is :

const events = require('events');
const WSS = 'ws://localhost:8881';
const provider = new Web3.providers.WebsocketProvider(WSS);
const web3 = new Web3(provider);
const eventEmitter = new events.EventEmitter();

myContract.events.MyEvent({
    //filter: {myIndexedParam: [20,23]},
    fromBlock: 0,
    toBlock: 'latest'
});

eventEmitter.on('data', e => {
    console.log(e.returnValues);
});

eventEmitter.on('error', e => {
    console.error(e);
});

// ...
// sending transaction
// ...


Answers 1


You are listening on an a wrong emitter. myContract.events.MyEvent returns an EventEmitter you have to listen to this. Check the documentation here https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#contract-events

You can try this method if what is explained in the documentation is not working.

const event = myContract.allEvents();

event.on('data', e => {
    console.log(e.returnValues);
});

//send transaction here

Also your myContract variable should hold the contract instance. see here

Sanjay S B
Sanjay S B
June 13, 2019 04:14 AM

Related Questions


Updated July 04, 2017 15:28 PM

Updated July 24, 2017 16:28 PM

Updated November 13, 2017 06:28 AM

Updated August 01, 2017 15:28 PM

Updated January 15, 2018 18:28 PM