1

I have following script. I want to do stopWatching after the event-logs are printed and automatically kill the running node, but via script I was not able to achive it.

run.js:

Web3 = require("web3");
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
exports.LogJob = function( blkNum ) {
    var event = myContractInstance.LogJob({}, { fromBlock: blkNum, toBlock: blkNum });
    event.watch( function (error, result) {
        console.log( JSON.stringify(result ) );                 
    });
    sleep.sleep(10);     //without those two lines it prints logs and pauses.
    event.stopWatching();//
}

ret = Log.Job( 100000 ); //I cannot return since watching is on.

Running: node run.js after printing logs does not kill itself and pauses like in a while(). Please note that if I have some other calls after calling LogJob() it always gives its output after everything is printed. So I can't return the output and do some operations.

If I do stopWatching() after 10 seconds within the function, now it does not print anything.

[Q] How could I print event logs and stopWatching() within the node script?

0

Please note that this works if and only if there is a log on the scanned blocks otherwise it pauses again. When we new input is feed in on the latest block process.exit() successfully.

I come up with following solution, it works and fixes the hanging issue:

run.js:

var fs = require('fs');
fs.unlinkSync("/tmp/test.txt");
Web3   = require("web3");
web3   = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

address="0x..." 
abi=[...]
var myContractInstance  = web3.eth.contract(mylib.abi).at(mylib.address);

var event = myContractInstance.LogJob({}, { fromBlock: blkNum, toBlock: 'latest' });
event.watch( function (error, result) {
    fs.appendFile( "/tmp/test.txt", JSON.stringify(result) + '\n', function(err) { 
       process.exit();
    });
}

After running node run.js we can find the output as follows:

cat /tmp/test.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.