Research
Security News
Malicious npm Package Targets Solana Developers and Hijacks Funds
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
The 'nats' npm package is a client library for the NATS messaging system, which is a high-performance, lightweight, and open-source messaging system for cloud-native applications, IoT messaging, and microservices architectures. It provides publish-subscribe, request-reply, and distributed queueing functionalities.
Publish-Subscribe
This feature allows you to publish messages to a subject and have multiple subscribers receive those messages. The code sample demonstrates how to set up a simple publish-subscribe system where a message is published to the 'updates' subject and received by a subscriber.
const { connect, StringCodec } = require('nats');
(async () => {
const nc = await connect({ servers: 'demo.nats.io:4222' });
const sc = StringCodec();
// Subscriber
const sub = nc.subscribe('updates');
(async () => {
for await (const m of sub) {
console.log(`Received a message: ${sc.decode(m.data)}`);
}
})();
// Publisher
nc.publish('updates', sc.encode('Hello, NATS!'));
})();
Request-Reply
This feature allows you to send a request and receive a reply, enabling synchronous communication between services. The code sample shows how to set up a responder that listens for requests on the 'help' subject and a requester that sends a request and waits for a reply.
const { connect, StringCodec } = require('nats');
(async () => {
const nc = await connect({ servers: 'demo.nats.io:4222' });
const sc = StringCodec();
// Responder
nc.subscribe('help', {
callback: (err, msg) => {
if (err) {
console.error(err);
} else {
msg.respond(sc.encode('I can help!'));
}
}
});
// Requester
const msg = await nc.request('help', sc.encode('Need assistance'), { timeout: 1000 });
console.log(`Received reply: ${sc.decode(msg.data)}`);
})();
Distributed Queueing
This feature allows you to distribute tasks among multiple workers, ensuring that each task is processed by only one worker. The code sample demonstrates how to set up two workers that listen on the 'tasks' subject and a publisher that sends tasks to be processed.
const { connect, StringCodec } = require('nats');
(async () => {
const nc = await connect({ servers: 'demo.nats.io:4222' });
const sc = StringCodec();
// Worker 1
nc.subscribe('tasks', { queue: 'workers' }, (err, msg) => {
if (err) {
console.error(err);
} else {
console.log(`Worker 1 received: ${sc.decode(msg.data)}`);
}
});
// Worker 2
nc.subscribe('tasks', { queue: 'workers' }, (err, msg) => {
if (err) {
console.error(err);
} else {
console.log(`Worker 2 received: ${sc.decode(msg.data)}`);
}
});
// Publisher
nc.publish('tasks', sc.encode('Task 1'));
nc.publish('tasks', sc.encode('Task 2'));
})();
The 'amqplib' package is a client for RabbitMQ, a widely-used message broker that supports multiple messaging protocols. Compared to NATS, RabbitMQ offers more advanced features like message persistence, complex routing, and transactions, but it is generally heavier and more complex to set up and manage.
The 'kafka-node' package is a client for Apache Kafka, a distributed streaming platform. Kafka is designed for high-throughput, fault-tolerant, and scalable messaging. It is more suitable for large-scale data streaming and log aggregation compared to NATS, which is more lightweight and easier to use for simple messaging needs.
The 'mqtt' package is a client for the MQTT protocol, which is designed for lightweight, low-bandwidth, and low-latency communication, often used in IoT applications. While NATS is also lightweight, MQTT is specifically optimized for constrained environments and offers features like last will and testament (LWT) messages.
A Node.js client for the NATS messaging system.
npm install nats
var nats = require('nats').connect();
// Simple Publisher
nats.publish('foo', 'Hello World!');
// Simple Subscriber
nats.subscribe('foo', function(msg) {
console.log('Received a message: ' + msg);
});
// Unsubscribing
var sid = nats.subscribe('foo', function(msg) {});
nats.unsubscribe(sid);
// Requests
nats.request('help', function(response) {
console.log('Got a response for help: ' + response);
});
// Replies
nats.subscribe('help', function(request, replyTo) {
nats.publish(replyTo, 'I can help!');
});
// Close connection
nats.close();
end
// "*" matches any token, at any level of the subject.
nats.subscribe('foo.*.baz', function(msg, reply, subject) {
console.log('Msg received on [' + subject + '] : ' + msg);
});
nats.subscribe('foo.bar.*', function(msg, reply, subject) {
console.log('Msg received on [' + subject + '] : ' + msg);
});
// ">" matches any length of the tail of a subject, and can only be the last token
// E.g. 'foo.>' will match 'foo.bar', 'foo.bar.baz', 'foo.foo.bar.bax.22'
nats.subscribe('foo.>', function(msg, reply, subject) {
console.log('Msg received on [' + subject + '] : ' + msg);
});
// All subscriptions with the same queue name will form a queue group.
// Each message will be delivered to only one subscriber per queue group, queuing semantics.
// You can have as many queue groups as you wish.
// Normal subscribers will continue to work as expected.
nats.subscribe('foo', {'queue':'job.workers'}, function() {
received += 1;
});
// Publish with closure, callback fires when server has processed the message
nats.publish('foo', 'You done?', function() {
console.log('msg processed!');
});
// Flush connection to server, callback fires when all messages have been processed.
nats.flush(function() {
console.log('All clear!');
});
// Timeouts for subscriptions
var sid = nats.subscribe('foo', function() {
received += 1;
});
// Timeout unless a certain number of messages have been received
nats.timeout(sid, timeout_ms, expected, function() {
timeout = true;
});
// Auto-unsubscribe after MAX_WANTED messages received
nats.subscribe('foo', {'max':MAX_WANTED});
nats.unsubscribe(sid, MAX_WANTED);
// Multiple connections
var nats = require('nats');
var nc1 = nats.connect();
var nc2 = nats.connect();
nc1.subscribe('foo');
nc2.publish('foo');
See examples and benchmarks for more information..
(The MIT License)
Copyright (c) 2011-2012 Derek Collison
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
Node.js client for NATS, a lightweight, high-performance cloud native messaging system
The npm package nats receives a total of 219,856 weekly downloads. As such, nats popularity was classified as popular.
We found that nats demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.