How to watch for the bitcoin transactions over blockchain via nodejs?

If you don't have your own node you can use blockchain.info APIs as described in here (https://github.com/blockchain/api-v1-client-node/tree/master/Socket)

const Socket = require('blockchain.info/Socket');
const mySocket = new Socket();
mySocket.onTransaction(function() {
  console.log(arguments);
});

You can always watch transactions by running your own node without the need to depend on a service like blockchain.info... For example, if you are using btcd (Golang) (https://github.com/btcsuite/btcd) then you can get notified on transactions like in here (http://godoc.org/github.com/btcsuite/btcrpcclient#Client.NotifyNewTransactions)


Using a third-party API, as the accepted answers suggests, will work in the short-term. But if you're looking for a long-term, reliable, not-rate-limited solution; you should run your own bitcoin node. It, of course, depends on your project's requirements.

For a robust solution to the OP's question, I suggest the following:

  • Run a pruned bitcoin node using bitcoind
  • Enable the ZeroMQ interface of bitcoind with the configuration option zmqpubrawtx=tcp://127.0.0.1:3600. This will enable streaming of raw transaction data to your node.js application
  • Use the ZeroMQ node.js module to subscribe to the bitcoind's ZeroMQ interface
  • Use bitcoinjs-lib to decode the raw transaction data

The following node.js example will use zeromq to subscribe to bitcoind's zeromq interface. Then bitcoinjs-lib is used to decode those raw transactions.

var bitcoin = require('bitcoinjs-lib');
var zmq = require('zeromq');
var sock = zmq.socket('sub');
var addr = 'tcp://127.0.0.1:3600';
sock.connect(addr);
sock.subscribe('rawtx');
sock.on('message', function(topic, message) {
    if (topic.toString() === 'rawtx') {
        var rawTx = message.toString('hex');
        var tx = bitcoin.Transaction.fromHex(rawTx);
        var txid = tx.getId();
        tx.ins = tx.ins.map(function(in) {
            in.address = bitcoin.address.fromOutputScript(in.script, bitcoin.networks.bitcoin);
            return in;
        });
        tx.outs = tx.outs.map(function(out) {
            out.address = bitcoin.address.fromOutputScript(out.script, bitcoin.networks.bitcoin);
            return out;
        });
        console.log('received transaction', txid, tx);
    }
});

For more details, please have a look at this guide


I think this is what you're looking for. The tutorial helps the user set up a local btc node and demonstrates how to use a zmq subscription along with RPC comms to accomplish sending and receiving transactions as well as notifications and other functionality.

@c.hill's response is correct but leaves out the more complicated functionality described here :)