[Ethereum] Listen to solidity events server-side

eventsnodejssolidity

I have a following contract:

pragma solidity ^0.4.17;

contract FileDetail {
 struct File{
    string fileName;
    string fileHash;
 }



 File[] private files;

 event Uploaded(
       string fileName,
       string fileHash
    );


 function setFile(string fName, string fileHash) public{
 File memory file = File({fileName:fName,fileHash:fileHash});
  files.push(file);
 emit Uploaded(fName,fileHash);
 }

 function getFile(uint256 index) external view returns(
 string fileName,
 string fileHash

 ){

   File memory file = files[index];
   fileName = file.fileName;
   fileHash = file.fileHash;

 }
}

I want to listen to the event emitted by this contract at server-side(not client-end) in Node.js. I want that a controller's method should be invoked when event is emitted so that I can save the values returned by contract in database.

Best Answer

You can do this as following,

var event = contract.myEvent();
event.watch((err, res) => {
    console.log(res); // event response
    // Do something on event;
    event.stopWatching() // Stop watching for the event once you've done what you wanted to do.
});

It would btw be pretty nice if you could also post your node.js code.

EDIT: Whats important to know is that if you are connected to infura (test or mainnet) you need to connect to their websocket provider and now their http provider, so instead of for example: https://mainnet.infura.io/ you have to insert wss://mainnet.infura.io/wsas provider.

Related Topic