nats-memory-server is a Node.js package that provides an in-memory NATS server for testing and other purposes. It allows you to quickly set up and tear down a NATS server instance within your Node.js applications, making it easier to write tests and perform other operations that require a NATS server.
- Go (Optional. Only if you build from source) (version 1.19 or later)
You can install nats-memory-server using npm or yarn:
npm install nats-memory-serveror
yarn add nats-memory-serverHere is a basic example of how to start and stop the NATS server using nats-memory-server and connect to it using the nats client.
const { NatsServerBuilder } = require('nats-memory-server');
const { connect, StringCodec } = require('nats');
(async () => {
// Start the server
// This will try to find a free port automatically if not specified
const server = await NatsServerBuilder.create().build().start();
const url = server.getUrl();
console.log(`NATS server started at ${url}`);
try {
// Connect to the server
const nc = await connect({ servers: url });
// Example: Publish and Subscribe
const sc = StringCodec();
const sub = nc.subscribe("hello");
(async () => {
for await (const m of sub) {
console.log(`[${sub.getProcessed()}]: ${sc.decode(m.data)}`);
}
})();
nc.publish("hello", sc.encode("world"));
// Ensure all messages are processed
await nc.drain();
} catch (err) {
console.error(err);
} finally {
// Stop the server
await server.stop();
}
})();For a runnable example, check example.js.
The configuration is used for two purposes:
- Installation: Determining which NATS server binary to download or build (handled during
postinstall). - Runtime: Configuring the server instance (port, ip, args, etc.).
You can configure the library using one of the following files:
nats-memory-server.jsonnats-memory-server.jsnats-memory-server.tspackage.json(undernatsMemoryServerkey)
{
"download": true,
"downloadDir": "node_modules/.cache/nats-memory-server",
"version": "v2.9.16",
"buildFromSource": false,
"binPath": "node_modules/.cache/nats-memory-server/nats-server",
"verbose": true,
"ip": "0.0.0.0"
}Installation Options:
download: (boolean) Whether to download the binary. Default:true.downloadDir: (string) Directory to download the binary to.version: (string) NATS server version to download. Default:v2.9.16.buildFromSource: (boolean) Whether to build from source instead of downloading. Default:false.binPath: (string) Path to the NATS server binary.httpProxy: (string) Proxy URL for HTTP requests.httpsProxy: (string) Proxy URL for HTTPS requests.noProxy: (string) Domain extensions to bypass the proxy.
Runtime Options:
port: (number) Port to listen on. If not specified, a free port is chosen.ip: (string) IP address to bind to. Default:0.0.0.0.verbose: (boolean) Enable verbose logging. Default:true.args: (string[]) Additional arguments to pass to the NATS server.
{
"version": "v2.9.16",
"verbose": false,
"port": 4222
}{
"natsMemoryServer": {
"version": "v2.9.16",
"port": 4222
}
}The builder class for creating NatsServer instances.
Creates a new NatsServerBuilder instance.
Sets the port number for the server.
Sets the IP address to bind to.
Enables or disables verbose logging.
Sets additional arguments for the NATS server executable.
Sets the path to the NATS server binary.
Sets a custom logger. The logger must implement log, error, warn, and debug methods.
Builds and returns a NatsServer instance.
The NATS server instance.
Starts the NATS server. Returns a promise that resolves to the server instance when ready.
Stops the NATS server.
Returns the connection URL (e.g., nats://0.0.0.0:4222).
Returns the host.
Returns the port.
To enable JetStream, you can use setArgs in the builder or pass it in the constructor options.
Using Builder:
const os = require('os');
const { NatsServerBuilder } = require('nats-memory-server');
await NatsServerBuilder
.create()
.setArgs(['--jetstream', '--store_dir', os.tmpdir()])
.build()
.start();Using Constructor:
const os = require('os');
const { NatsServer, DEFAULT_NATS_SERVER_OPTIONS } = require('nats-memory-server');
new NatsServer({
...DEFAULT_NATS_SERVER_OPTIONS,
args: ['--jetstream', '--store_dir', os.tmpdir()],
});Contributions are welcome! If you find any issues or have suggestions for improvement, please feel free to open an issue or submit a pull request on the GitHub repository.
When contributing, please ensure to follow the code of conduct.