To retrieve pending messages from an ActiveMQ broker in Node.js, you can use the `stompit` library, which provides a STOMP (Simple Text Oriented Messaging Protocol) client for Node.js. STOMP is a common protocol for interacting with message brokers like ActiveMQ. Here's a basic example of how to connect to ActiveMQ and consume pending messages in Node.js:
1. Install the `stompit` library:
```bash
npm install stompit
```
2. Create a Node.js script to connect to ActiveMQ and consume pending messages:
```javascript
const stompit = require('stompit');
const serverConfig = {
host: 'localhost', // ActiveMQ server host
port: 61613, // ActiveMQ STOMP port (usually 61613)
connectHeaders: {
host: 'my-broker',
login: 'your-username', // Replace with your ActiveMQ username
passcode: 'your-password', // Replace with your ActiveMQ password
'heart-beat': '5000,5000'
},
};
// Connect to the ActiveMQ broker
stompit.connect(serverConfig, (error, client) => {
if (error) {
console.error('Error connecting to ActiveMQ:', error.message);
return;
}
console.log('Connected to ActiveMQ');
// Subscribe to the queue
const subscribeHeaders = {
destination: '/queue/your-queue-name', // Replace with your queue name
ack: 'auto',
};
client.subscribe(subscribeHeaders, (error, message) => {
if (error) {
console.error('Error subscribing to the queue:', error.message);
return;
}
message.readString('utf-8', (error, body) => {
if (error) {
console.error('Error reading message:', error.message);
} else {
console.log('Received message:', body);
}
client.disconnect();
});
});
});
```
In this script:
- Replace `'localhost'` with the hostname or IP address of your ActiveMQ server.
- Adjust the `port`, `login`, `passcode`, `destination` (queue name), and other parameters to match your ActiveMQ configuration.
- The script connects to ActiveMQ, subscribes to the specified queue, and processes the pending messages as they arrive.
Make sure to secure your credentials and adjust the error handling and processing logic as needed for your specific use case.