Registry / database / node-redis-pubsub

node-redis-pubsub

JSON →
library5.0.0jsnpmunverified

Node Redis Pubsub (NRP) is a JavaScript library designed to simplify the use of Redis's Pub/Sub functionality within Node.js applications. It abstracts away the complex raw Redis Pub/Sub API, providing a more intuitive, event emitter-like interface. NRP is particularly valuable for inter-application communication, allowing different Node.js instances or even other services to share data via a central Redis server, a capability not offered by Node's built-in EventEmitter. The library is currently at version 5.0.0 and demonstrates active maintenance, including recent updates to address non-JSON payload handling and significant API refactorings for subscription management. While its release cadence isn't explicitly defined, the project shows ongoing development and recent shifts in maintainership. Key differentiators include its `scope` option to prevent message collisions between different NRP instances, support for reusing existing Redis client connections, and robust error handling.

npm install node-redis-pubsub
INSTALL
IMPORT
SIG · NODE-REDIS-PUBSUB
N
node-redis-pubsub
databasejavascriptv5.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

NRP
import NRP from 'node-redis-pubsub';
import { NRP } from 'node-redis-pubsub';
For ESM environments, the `NRP` class is typically imported as the default export. Avoid named imports for the main class.
NRP
const NRP = require('node-redis-pubsub');
const NRP = require('node-redis-pubsub').NRP;
For CommonJS environments, the `NRP` class is the module's default export. Destructuring `NRP` from the `require` call is incorrect.
Config types (inferred)
import type { RedisClientOptions } from 'redis'; // for configuration types
While `node-redis-pubsub` does not export its own specific configuration types, its `config` object largely mirrors options from the underlying `redis` client library. For advanced type-checking in TypeScript, refer to `redis` package types like `RedisClientOptions`.

This quickstart demonstrates basic setup for Node Redis PubSub (NRP), including connecting to Redis, subscribing to specific events and patterns, emitting messages, unsubscribing from events, and proper error handling and connection shutdown. It simulates a simple producer-consumer scenario.

const NRP = require('node-redis-pubsub'); // Configure NRP, connecting to a local Redis instance or using an environment variable // Ensure REDIS_URL is set or a local Redis server is running on 6379 const config = process.env.REDIS_URL ? { url: process.env.REDIS_URL } : { port: 6379, // Default Redis port host: '127.0.0.1', scope: 'my-app-scope' // Isolate messages for this application }; const nrp = new NRP(config); // This is the NRP client instance // --- Simple PubSub example --- // Subscribe to 'say hello' messages nrp.on('say hello', (data) => { console.log(`[Subscriber] Hello ${data?.name ?? 'Unknown'} from NRP!`); }); // Subscribe to messages matching a pattern nrp.on('city:*', (data, channel) => { console.log(`[Subscriber] Received city message on channel '${channel}': ${data?.city ?? 'Unknown city'} is a great city.`); }); // Emit messages after a short delay to ensure listeners are registered setTimeout(() => { console.log('[Emitter] Emitting "say hello"'); nrp.emit('say hello', { name: 'Registry Agent' }); console.log('[Emitter] Emitting "city:paris"'); nrp.emit('city:paris', { city: 'Paris' }); console.log('[Emitter] Emitting "city:london"'); nrp.emit('city:london', { city: 'London' }); // Example of unsubscribing after a message console.log('[Emitter] Setting up a one-time greeting'); const unsubscribeGreet = nrp.on('greet_once', (data) => { console.log(`[Subscriber] Greeting once: ${data?.message ?? 'No message'}`); unsubscribeGreet(); // Unsubscribe immediately after first message }); console.log('[Emitter] Emitting "greet_once" (first time)'); nrp.emit('greet_once', { message: 'This message should only appear once.' }); console.log('[Emitter] Emitting "greet_once" (second time - should not be received)'); nrp.emit('greet_once', { message: 'This message should NOT appear.' }); }, 500); // Listen for errors from the underlying Redis connections nrp.on("error", (err) => { console.error("NRP Error:", err.message); }); // Shut down connections safely after a period setTimeout(() => { console.log('Quitting NRP connections safely...'); nrp.quit(); console.log('NRP connections closed.'); }, 2000);
Debug
Known issues
breakingVersion 1.0.0 introduced significant breaking changes by removing the `.off()` and `.unsubscribe()` methods. The new API requires calling the unsubscribe function returned directly by `.on()` or `.subscribe()`.
fix
Replace calls to `nrp.off('event')` or `nrp.unsubscribe('event')` with storing the return value of `nrp.on('event', handler)` and calling that returned function, e.g., `const unsubscribe = nrp.on('event', handler); unsubscribe();`
affects: >=1.0.0
gotchaCare must be taken to ensure that a subscriber (via `.on` or `.subscribe`) is fully registered with Redis before an emitter sends a message. While the library handles basic race conditions with a callback on `.on`, direct `emit`s might still be missed if the `on` call hasn't completed its subscription process.
fix
Utilize the optional callback parameter provided by `.on(channel, handler, callback)` to ensure the subscription is active before emitting. Alternatively, introduce a small delay or a more robust synchronization mechanism in distributed systems for critical messages.
affects: >=1.0.0
gotchaUnderstanding the difference between `nrp.quit()` and `nrp.end()` is crucial for graceful shutdown. `quit()` attempts a safe shutdown, waiting for all commands to complete, while `end()` immediately terminates connections, potentially losing in-flight messages.
fix
Always prefer `nrp.quit()` for graceful application shutdown to ensure all pending messages are processed and connections are closed cleanly. Use `nrp.end()` only in exceptional circumstances where immediate termination is required, acknowledging potential data loss.
affects: >=1.0.0
gotchaThe `scope` configuration option is essential to prevent message collisions if multiple NRP instances (even for different applications) share the same Redis server. Without a unique scope, all messages on the same channel would be received by all instances, leading to unintended behavior.
fix
Always configure a unique `scope` for each distinct application or module using `node-redis-pubsub` to ensure message isolation, for example: `{ scope: 'my-app-production' }`.
affects: >=1.0.0
Errors
Common errors & fixes
Error: Redis connection to 127.0.0.1:6379 refused - connect ECONNREFUSED
The Redis server is either not running, or it's running on a different host/port than configured in NRP.
fix
Ensure your Redis server is running and accessible from the Node.js application. Verify that the `host` and `port` in your NRP configuration (or the `REDIS_URL` environment variable) accurately match your Redis server's address and listening port.
TypeError: NRP is not a constructor
The `NRP` class was not correctly imported or required from the `node-redis-pubsub` module, often due to incorrect import syntax.
fix
For CommonJS modules, use `const NRP = require('node-redis-pubsub');`. For ESM modules, use `import NRP from 'node-redis-pubsub';`. Do not attempt named imports like `{ NRP }` for the main class.
Error: ERR invalid password
The Redis server requires authentication, but the `auth` password was not provided or is incorrect in the NRP configuration.
fix
Provide the correct authentication password in the NRP configuration object (e.g., `{ auth: 'your_redis_password' }`). If using a `REDIS_URL`, ensure the password is included in the URL string (e.g., `redis://:password@host:port`).
Message not received by subscriber
An `emit` call happened before the corresponding `on` subscription was fully established and confirmed by the Redis server, leading to a race condition where the message was sent before a listener was ready.
fix
To prevent this race condition, use the optional callback parameter of `nrp.on(channel, handler, callback)` to ensure the subscription is confirmed active before emitting the message. For example: `nrp.on('event', handler, () => nrp.emit('event', data));`
Upgrade
Version history
5.0.0latest on npm
Audit
Dependencies
redisrequiredCore dependency for connecting to and interacting with the Redis server for pub/sub operations.
Agent activity
13 hits · last 30 days
node
12
OpenAI (training)
1
Resources
node-redis-pubsub — npm install node-redis-pubsub · libregistry