Subscribe to a topic
After you create the topic, you will want to subscribe to the topic via a Hedera mirror node. Subscribing to a topic via a Hedera mirror node allows you to receive the stream of messages that are being submitted to it.
Step 1 : Imports
The script imports necessary modules from the Hedera JavaScript SDK:
TopicMessageQuery,Client, andPrivateKey.It also imports the
dotenvmodule to load environment variables from a.envfile located in theConsensus_Servicedirectory.
const {
TopicMessageQuery,
Client,
PrivateKey
} = require("@hashgraph/sdk");
require('dotenv').config({ path: 'Consensus_Service/.env' });Step 2 : Environment Variables Retrieval
These lines retrieve environment variables such as MY_ACCOUNT_ID, MY_PRIVATE_KEY, and TOPIC_ID from the .env file using process.env.
const myAccountId = process.env.MY_ACCOUNT_ID;
const myPrivateKey = PrivateKey.fromString(process.env.MY_PRIVATE_KEY);
const topicId = process.env.TOPIC_ID;Step 3: Validation
This block of code ensures that the required environment variables (MY_ACCOUNT_ID and MY_PRIVATE_KEY) are present. If not, it throws an error.
Step 3 : Main Function
This is the main function named
main().It creates a client instance for the Hedera testnet and sets the operator account using the user's account ID and private key.
It creates a new
TopicMessageQueryobject to subscribe to a topic.The topic ID and start time are set using the retrieved environment variables.
The script subscribes to the topic using the
subscribe()method. Incoming messages are logged to the console.
This script subscribes to a consensus topic on the Hedera network and listens for incoming messages. When a message is received, it is logged to the console.
Last updated
Was this helpful?