Construct a new Aerospike client instance.
Configuration used to initialize the client.
Set to true
to enable capturing of debug stacktraces for
every database command.
The client will capture a stacktrace before each database command is executed, instead of capturing the stacktrace only when an error is raised. This generally results in much more useful stacktraces that include stackframes from the calling application issuing the database command.
Note: Enabling this feature incurs a significant performance overhead for every database command. It is recommended to leave this feature disabled in production environments.
By default, the client will set this flag to true, if the
AEROSPIKE_DEBUG_STACKTRACES
environment variable is set (to
any value).
A copy of the configuration with which the client was initialized.
Static
captureValue: boolean
Change the default captureRejections
option on all new EventEmitter
objects.
Static
Readonly
captureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler
.
Static
defaultBy default, a maximum of 10
listeners can be registered for any single
event. This limit can be changed for individual EventEmitter
instances
using the emitter.setMaxListeners(n)
method. To change the default
for allEventEmitter
instances, the events.defaultMaxListeners
property
can be used. If this value is not a positive number, a RangeError
is thrown.
Take caution when setting the events.defaultMaxListeners
because the
change affects all EventEmitter
instances, including those created before
the change is made. However, calling emitter.setMaxListeners(n)
still has
precedence over events.defaultMaxListeners
.
This is not a hard limit. The EventEmitter
instance will allow
more listeners to be added but will output a trace warning to stderr indicating
that a "possible EventEmitter memory leak" has been detected. For any single
EventEmitter
, the emitter.getMaxListeners()
and emitter.setMaxListeners()
methods can be used to
temporarily avoid this warning:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
The --trace-warnings
command-line flag can be used to display the
stack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will
have the additional emitter
, type
, and count
properties, referring to
the event emitter instance, the event's name and the number of attached
listeners, respectively.
Its name
property is set to 'MaxListenersExceededWarning'
.
Static
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular 'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an 'error'
event is emitted. Therefore, the process will still crash if no
regular 'error'
listener is installed.
Optional
[captureRest
...args: AnyRestTransaction instance.
This function will be called with the result returned by the abort function call.
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
read : new Aerospike.ReadPolicy({socketTimeout : 0, totalTimeout : 0}),
write : new Aerospike.WritePolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
let key1 = new Aerospike.Key('test', 'demo', 'myKey')
let key2 = new Aerospike.Key('test', 'demo', 'myKey')
let record1 = {abc: 123}
let record2 = {def: 456}
;(async () => {
let client = await Aerospike.connect(config)
const policy = {
txn: tran
}
await client.put(key4, record2, meta, policy)
const policyRead = {
txn: tran
}
let get_result = await client.get(key1, policy) // Will reflect the new value recently put.
await client.put(key2, record2, meta, policy)
let result = await client.abort(tran)
get_result = await client.get(key4) // Will reset to the value present before transaction started.
get_result = await client.get(key5) // Will reset to the value present before transaction started.
await client.close()
})();
Transaction instance.
A Promise that resolves to the value returned by abort.
Shortcut for applying the operations.add operation to one or more record bins.
The key of the record.
The key-value mapping of bin names and the corresponding values to use to increment the bin values with.
Optional
metadata: null | RecordMetadataMeta data.
Optional
policy: null | policy.OperatePolicyThe Operate Policy to use for this command.
A Promise that resolves to the results of the opertion.
The key of the record.
The key-value mapping of bin names and the corresponding values to use to increment the bin values with.
The function to call when the command completes with the results of the command.
The key of the record.
The key-value mapping of bin names and the corresponding values to use to increment the bin values with.
The function to call when the command completes with the results of the command.
The key of the record.
The key-value mapping of bin names and the corresponding values to use to increment the bin values with.
Meta data.
The function to call when the command completes with the results of the command.
Alias for emitter.on(eventName, listener)
.
Rest
...args: any[]Adds a seed host to the cluster.
Hostname/IP address of the new seed host
Optional
port: numberPort number; defaults to Config#port or 3000.
Shortcut for applying the operations.append operation to one or more record bins.
The key of the record.
The key-value mapping of bin names and the corresponding values to append to the bin value. The bins must contain either string or byte array values and the values to append must be of the same type.
Optional
metadata: null | RecordMetadataMeta data.
Optional
policy: null | policy.OperatePolicyThe Operate Policy to use for this command.
A Promise that resolves to the results of the opertion.
This function works on bins of type string or bytes; to append a new value (of any type) to a bin containing a list of existing values, use the lists.append operation instead.
The key of the record.
The key-value mapping of bin names and the corresponding values to append to the bin value. The bins must contain either string or byte array values and the values to append must be of the same type.
The function to call when the command completes with the results of the command.
The key of the record.
The key-value mapping of bin names and the corresponding values to append to the bin value. The bins must contain either string or byte array values and the values to append must be of the same type.
Meta data.
The function to call when the command completes with the results of the command.
The key of the record.
The key-value mapping of bin names and the corresponding values to append to the bin value. The bins must contain either string or byte array values and the values to append must be of the same type.
Meta data.
The Operate Policy to use for this command.
The function to call when the command completes with the results of the command.
Applies a User Defined Function (UDF) on a record in the database.
The key, used to locate the record in the cluster.
Parameters used to specify which UDF function to execute.
Optional
policy: null | policy.ApplyPolicyThe Apply Policy to use for this command.
A Promise that resolves to the value returned by the UDF.
Use this function to apply a ⇑Record UDF on a single record and return the result of the UDF function call. Record UDFs can be used to augment both read and write behavior.
For additional information please refer to the section on ⇑Developing Record UDFs in the Aerospike technical documentation.
apply()
.const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
const config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
apply : new Aerospike.ApplyPolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
var key = new Aerospike.Key('test', 'demo', 'value')
var udfArgs = {
module: 'my_udf_module',
funcname: 'my_udf_function',
args: ['abc', 123, 4.5]
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
client.apply(key, udfArgs, (error, result) => {
if (error) throw error
console.log('Result of calling my_udf_function:', result)
})
})
The key, used to locate the record in the cluster.
Parameters used to specify which UDF function to execute.
This function will be called with the result returned by the Record UDF function call.
The key, used to locate the record in the cluster.
Parameters used to specify which UDF function to execute.
The Apply Policy to use for this command.
This function will be called with the result returned by the Record UDF function call.
Apply UDF (user defined function) on multiple keys.
An array of keys, used to locate the records in the cluster.
Server UDF module/function and argList to apply.
Optional
batchPolicy: null | policy.BatchPolicyThe Batch Policy to use for this command.
Optional
batchApplyPolicy: null | policy.BatchApplyPolicyUDF policy configuration parameters.
A Promise that resolves to the results of the batched command.
This method allows multiple sub-commands for each key in the batch. This method requires server >= 6.0.0.
const Aerospike = require('aerospike')
var path = require('path');
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
const config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
// This must be a path to a UDF file
const scriptLocation = path.join(__dirname, 'udf-list.lua')
;(async () => {
// Establishes a connection to the server
let client = await Aerospike.connect(config);
// Place some records for demonstration
await client.put(new Aerospike.Key('test', 'demo', 'key1'), {example: 30})
await client.put(new Aerospike.Key('test', 'demo', 'key2'), {example: 35})
await client.udfRegister(scriptLocation)
// Execute the UDF
let batchResult = await client.batchApply([new Aerospike.Key('test', 'demo', 'key1'), new Aerospike.Key('test', 'demo', 'key2')],
{
module: 'udf-list',
funcname: 'updateRecord',
args: ['example', 45]
}
);
// Access the records
batchResult.forEach(result => {
// Do something
console.info("New value of example bin is %o \n", result.record.bins.SUCCESS);
});
//Additional verfication
let result = await client.get(new Aerospike.Key('test', 'demo', 'key1'))
console.log(result.bins) // { example: 45 }
result = await client.get(new Aerospike.Key('test', 'demo', 'key2'))
console.log(result.bins) // { example: 45 }
// Close the connection to the server
await client.close();
})(); *
An array of keys, used to locate the records in the cluster.
Server UDF module/function and argList to apply.
Optional
callback: TypedCallback<BatchResult[]>The function to call when the command completes. Includes the results of the batched command.
An array of keys, used to locate the records in the cluster.
Server UDF module/function and argList to apply.
Optional
batchPolicy: policy.BatchPolicyThe Batch Policy to use for this command.
Optional
callback: TypedCallback<BatchResult[]>The function to call when the command completes, with the results of the batched command.
An array of keys, used to locate the records in the cluster.
Server UDF module/function and argList to apply.
Optional
batchPolicy: policy.BatchPolicyThe Batch Policy to use for this command.
Optional
batchApplyPolicy: policy.BatchApplyPolicyUDF policy configuration parameters.
Optional
callback: TypedCallback<BatchResult[]>The function to call when the command completes, with the results of the batched command.
Checks the existence of a batch of records from the database cluster.
An array of Keys used to locate the records in the cluster.
Optional
policy: null | policy.BatchPolicyThe Batch Policy to use for this command.
A Promise that resolves to the results of the batched command.
since v2.0 - use Client#batchRead instead.
const Aerospike = require('aerospike')
const Key = Aerospike.Key
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
var keys = [
new Key('test', 'demo', 'key1'),
new Key('test', 'demo', 'key2'),
new Key('test', 'demo', 'key3')
]
;(async () => {
// Establishes a connection to the server
let client = await Aerospike.connect(config);
// Place some records for demonstration
await client.put(keys[0], {example: 30})
await client.put(keys[1], {example: 35})
await client.put(keys[2], {example: 40})
let results = await client.batchExists(keys)
results.forEach((result) => {
switch (result.status) {
case Aerospike.status.OK:
console.log("Record found")
break
case Aerospike.status.ERR_RECORD_NOT_FOUND:
console.log("Record not found")
break
default:
// error while reading record
console.log("Other error")
break
}
})
// Close the connection to the server
await client.close();
})();
An array of Keys used to locate the records in the cluster.
The function to call when the command completes, with the results of the batched command.
An array of Keys used to locate the records in the cluster.
The Batch Policy to use for this command.
The function to call when the command completes, with the results of the batched command.
Reads a batch of records from the database cluster.
An array of Keys, used to locate the records in the cluster.
Optional
policy: null | policy.BatchPolicyThe Batch Policy to use for this command.
since v2.0 - use Client#batchRead instead.
const Aerospike = require('aerospike')
const Key = Aerospike.Key
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
var keys = [
new Key('test', 'demo', 'key1'),
new Key('test', 'demo', 'key2'),
new Key('test', 'demo', 'key3')
]
;(async () => {
// Establishes a connection to the server
let client = await Aerospike.connect(config);
// Place some records for demonstration
await client.put(keys[0], {example: 30})
await client.put(keys[1], {example: 35})
await client.put(keys[2], {example: 40})
let results = await client.batchGet(keys)
results.forEach((result) => {
switch (result.status) {
case Aerospike.status.OK:
console.log("Record found")
break
case Aerospike.status.ERR_RECORD_NOT_FOUND:
console.log("Record not found")
break
default:
// error while reading record
console.log("Other error")
break
}
})
// Close the connection to the server
await client.close();
})();
An array of Keys, used to locate the records in the cluster.
The function to call when the command completes, with the results of the batched command.
An array of Keys, used to locate the records in the cluster.
The Batch Policy to use for this command.
The function to call when the command completes, with the results of the batched command.
Read multiple records for specified batch keys in one batch call.
List of BatchReadRecord instances which each contain keys and bins to retrieve.
Optional
policy: policy.BatchPolicyThe Batch Policy to use for this command.
This method allows different namespaces/bins to be requested for each key in the batch. This method requires server >= 3.6.0.
const Aerospike = require('aerospike')
const batchType = Aerospike.batchType
const op = Aerospike.operations
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
var batchRecords = [
{ type: batchType.BATCH_READ,
key: new Aerospike.Key('test', 'demo', 'key1'), bins: ['example'] },
{ type: batchType.BATCH_READ,
key: new Aerospike.Key('test', 'demo', 'key2'), readAllBins: true },
{ type: batchType.BATCH_READ,
key: new Aerospike.Key('test', 'demo', 'key3'),
ops:[
op.read('example')
]},
{ type: batchType.BATCH_READ,
key: new Aerospike.Key('test', 'demo', 'key4')}
]
;(async () => {
// Establishes a connection to the server
let client = await Aerospike.connect(config);
// Place some records for demonstration
await client.put(batchRecords[0].key, {example: 30})
await client.put(batchRecords[1].key, {example: 35})
await client.put(batchRecords[2].key, {example: 40})
await client.put(batchRecords[3].key, {example: 45})
let results = await client.batchRead(batchRecords)
results.forEach((result) => {
switch (result.status) {
case Aerospike.status.OK:
console.log("Record found")
// Since the fourth record didn't specify bins to read,
// the fourth record will return no bins, eventhough the batchRead succeeded.
console.log(result.record.bins)
break
case Aerospike.status.ERR_RECORD_NOT_FOUND:
console.log("Record not found")
break
default:
// error while reading record
console.log("Other error")
break
}
})
// Close the connection to the server
await client.close();
})();
List of BatchReadRecord instances which each contain keys and bins to retrieve.
Optional
callback: TypedCallback<BatchResult[]>The function to call when the command completes, with the results of the batched command.
List of BatchReadRecord instances which each contain keys and bins to retrieve.
Optional
policy: null | policy.BatchPolicyThe Batch Policy to use for this command.
Optional
callback: TypedCallback<BatchResult[]>The function to call when the command completes, with the results of the batched command.
Remove multiple records.
Key An array of keys, used to locate the records in the cluster.
Optional
batchPolicy: null | policy.BatchPolicyThe Batch Policy to use for this command.
Optional
batchRemovePolicy: null | policy.BatchRemovePolicyRemove policy configuration parameters.
A Promise that resolves to the results of the batched command.
This method removes the specified records from the database. This method requires server >= 6.0.0.
const Aerospike = require('aerospike')
const batchType = Aerospike.batchType
const exp = Aerospike.exp
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
var keys = [
new Aerospike.Key('test', 'demo', 'key1'),
new Aerospike.Key('test', 'demo', 'key2'),
new Aerospike.Key('test', 'demo', 'key3')
]
;(async () => {
// Establishes a connection to the server
let client = await Aerospike.connect(config);
// Place some records for demonstration
await client.put(keys[0], {example: 30})
await client.put(keys[1], {example: 35})
let results = await client.batchRemove(keys)
results.forEach((result) => {
switch (result.status) {
case Aerospike.status.OK:
console.log("Record deleted")
break
case Aerospike.status.ERR_RECORD_NOT_FOUND:
console.log("Record not found")
break
default:
// error while reading record
console.log("Other error")
break
}
})
// Close the connection to the server
await client.close();
})();
Key An array of keys, used to locate the records in the cluster.
Optional
callback: TypedCallback<BatchResult[]>The function to call when the command completes, with the results of the batched command.
Key An array of keys, used to locate the records in the cluster.
Optional
batchPolicy: null | policy.BatchPolicyThe Batch Policy to use for this command.
Optional
callback: TypedCallback<BatchResult[]>The function to call when the command completes, with the results of the batched command.
Key An array of keys, used to locate the records in the cluster.
Optional
batchPolicy: null | policy.BatchPolicyThe Batch Policy to use for this command.
Optional
batchRemovePolicy: null | policy.BatchRemovePolicyRemove policy configuration parameters.
Optional
callback: TypedCallback<BatchResult[]>The function to call when the command completes, with the results of the batched command.
Reads a subset of bins for a batch of records from the database cluster.
An array of keys, used to locate the records in the cluster.
An array of bin names for the bins to be returned for the given keys.
Optional
policy: policy.BatchPolicyThe Batch Policy to use for this command.
since v2.0 - use Client#batchRead instead.
const Aerospike = require('aerospike')
const batchType = Aerospike.batchType
const exp = Aerospike.exp
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
var keys = [
new Aerospike.Key('test', 'demo', 'key1'),
new Aerospike.Key('test', 'demo', 'key2'),
new Aerospike.Key('test', 'demo', 'key3')
]
var bins = ['example', 'user']
;(async () => {
// Establishes a connection to the server
let client = await Aerospike.connect(config);
// Place some records for demonstration
await client.put(keys[0], {example: 30, user: 'Doug', extra: 'unused'})
await client.put(keys[1], {example: 35})
let results = await client.batchSelect(keys, bins)
results.forEach((result) => {
switch (result.status) {
case Aerospike.status.OK:
console.log("Record found")
// Since the fourth record didn't specify bins to read,
// the fourth record will return no bins, eventhough the batchRead succeeded.
console.log(result.record.bins)
break
case Aerospike.status.ERR_RECORD_NOT_FOUND:
console.log("Record not found")
break
default:
// error while reading record
console.log("Other error")
break
}
})
// Close the connection to the server
await client.close();
})();
An array of keys, used to locate the records in the cluster.
An array of bin names for the bins to be returned for the given keys.
The function to call when the command completes, with the results of the batched command.
An array of keys, used to locate the records in the cluster.
An array of bin names for the bins to be returned for the given keys.
The Batch Policy to use for this command.
The function to call when the command completes, with the results of the batched command.
Read/Write multiple records for specified batch keys in one batch call.
This method allows different sub-commands for each key in the batch. This method requires server >= 6.0.0.
List of BatchWriteRecord instances which each contain keys and bins to retrieve.
Optional
policy: null | policy.BatchPolicyThe Batch Policy to use for this command.
const Aerospike = require('aerospike')
const batchType = Aerospike.batchType
const Key = Aerospike.Key
const op = Aerospike.operations
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
batch : new Aerospike.BatchPolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
const batchRecords = [
{
type: batchType.BATCH_REMOVE,
key: new Key("test", "demo", 'key1')
},
{
type: batchType.BATCH_WRITE,
key: new Key("test", "demo", 'key2'),
ops: [
op.write('example', 30),
op.write('blob', Buffer.from('foo'))
],
policy: new Aerospike.BatchWritePolicy({
exists: Aerospike.policy.exists.IGNORE
})
},
{
type: batchType.BATCH_WRITE,
key: new Key("test", "demo", 'key3'),
ops: [
op.write('example', 35),
op.write('blob', Buffer.from('bar'))
],
policy: new Aerospike.BatchWritePolicy({
exists: Aerospike.policy.exists.IGNORE
})
}
]
const batchReadRecords = [
{
type: batchType.BATCH_READ,
key: new Key("test", "demo", 'key1'),
readAllBins: true
},
{
type: batchType.BATCH_READ,
key: new Key("test", "demo", 'key2'),
readAllBins: true
},
{
type: batchType.BATCH_READ,
key: new Key("test", "demo", 'key3'),
readAllBins: true
}
]
;(async () => {
// Establishes a connection to the server
let client = await Aerospike.connect(config);
// Place a record for demonstration
await client.put(new Key("test", "demo", 'key1'), {example: 30, user: 'Doug', extra: 'unused'})
let results = await client.batchWrite(batchRecords)
results.forEach((result) => {
switch (result.status) {
case Aerospike.status.OK:
console.log("Record found")
break
case Aerospike.status.ERR_RECORD_NOT_FOUND:
console.log("Record not found")
break
default:
// error while reading record
console.log("Other error")
break
}
})
results = await client.batchWrite(batchRecords)
results.forEach((result) => {
switch (result.status) {
case Aerospike.status.OK:
console.log("Record found")
break
case Aerospike.status.ERR_RECORD_NOT_FOUND:
console.log("Record not found")
break
default:
// error while reading record
console.log("Other error")
break
}
})
// Close the connection to the server
await client.close();
})();
List of BatchWriteRecord instances which each contain keys and bins to retrieve.
Optional
callback: TypedCallback<BatchResult[]>The function to call when the command completes, Includes the results of the batched command.
List of BatchWriteRecord instances which each contain keys and bins to retrieve.
Optional
policy: policy.BatchPolicyThe Batch Policy to use for this command.
Optional
callback: TypedCallback<BatchResult[]>The function to call when the command completes, Includes the results of the batched command.
Client#changePassword
Change a user's password.
User name for the password change.
User password in clear-text format.
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
// User must be created before password is changed. See {@link Client#createUser} for an example.
client.changePassword("khob", "TryTiger7!", ["Engineer"])
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
Closes the client connection to the cluster.
Optional
releaseEventLoop: booleanWhether to release the event loop handle after the client is closed. Default is false
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config)
.then(client => {
// client is ready to accept commands
console.log("Connected. Now Closing Connection.")
client.close()
})
.catch(error => {
* client.close()
console.error('Failed to connect to cluster: %s', error.message)
})
Transaction instance.
This function will be called with the result returned by the commit function call.
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
let bins = {
int: 123,
double: 3.1415,
string: 'xyz',
bytes: Buffer.from('hello world!'),
list: [1, 2, 3],
map: {num: 123, str: 'abc', list: ['a', 'b', 'c']}
}
let meta = {
ttl: 386400 // 1 day
}
let key1 = new Aerospike.Key('test', 'demo', 'myKey1')
let key2 = new Aerospike.Key('test', 'demo', 'myKey2')
let policy = {
txn: tran
};
;(async () => {
let client = await Aerospike.connect(config)
let tran = new Aerospike.Transaction()
await client.put(key1, bins, meta, policy)
await client.put(key2, bins, meta, policy)
let get_result = await client.get(key1, policy)
let result = await client.commit(tran)
await client.close()
})();
Transaction instance.
A Promise that resolves to the Transaction.commitStatus returned by commit.
})();
Establishes the connection to the cluster.
Optional
callback: TypedCallback<Client>The function to call once the client connection has been established successfully and the client is ready to accept commands.
If no callback function is passed, the function returns a Promise resolving to the connected client.
Once the client is connected to at least one server node, it will start polling each cluster node regularly to discover the current cluster status. As new nodes are added to the cluster, or existing nodes are removed, the client will establish or close down connections to these nodes. If the client gets disconnected from the cluster, it will keep polling the last known server endpoints, and will reconnect automatically if the connection is reestablished.
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
if (error) {
console.error('Failed to connect to cluster: %s', error.message)
process.exit()
} else {
// client is ready to accept commands
console.log("Connected. Now closing connection.")
client.close()
}
})
Returns a deserialized CDT Context
base64 serialized {link cdt.Context}
Deserialized CDT Context
contextFromBase64 for a usage example.
Returns a serialized CDT Context
serialized context - base64 representation of the CDT Context
const Aerospike = require('aerospike');
const Context = Aerospike.cdt.Context
// Define host configuration
let config = {
hosts: '192.168.33.10:3000',
policies: {
operate : new Aerospike.OperatePolicy({socketTimeout : 0, totalTimeout : 0}),
write : new Aerospike.WritePolicy({socketTimeout : 0, totalTimeout : 0}),
read : new Aerospike.ReadPolicy({socketTimeout : 0, totalTimeout : 0})
}
}
Aerospike.connect(config, async (error, client) => {
// Create a context
let context = new Context().addMapKey('nested')
// Create keys for records to be written
let recordKey = new Aerospike.Key('test', 'demo', 'record')
let contextKey = new Aerospike.Key('test', 'demo', 'context')
// Put record with a CDT
await client.put(recordKey, {exampleBin: {nested: {food: 'blueberry', drink: 'koolaid'}}})
// Test the context with client.operate()
var ops = [
Aerospike.maps.getByKey('exampleBin', 'food', Aerospike.maps.returnType.KEY_VALUE).withContext(context)
]
let results = await client.operate(recordKey, ops)
console.log(results.bins.exampleBin) // [ 'food', 'blueberry' ]
// Serialize CDT Context
let serializedContext = client.contextToBase64(context)
// Put record with bin containing the serialized record
await client.put(contextKey, {context: serializedContext})
// Get context when needed for command
let contextRecord = await client.get(contextKey)
// Deserialize CDT Context
context = client.contextFromBase64(contextRecord.bins.context)
// Test the context with client.operate()
ops = [
Aerospike.maps.getByKey('exampleBin', 'food', Aerospike.maps.returnType.KEY_VALUE).withContext(context)
]
results = await client.operate(recordKey, ops)
console.log(results.bins.exampleBin) // [ 'food', 'blueberry' ]
// Close the client
client.close()
})
Creates a blob secondary index index.
This is a short-hand for calling Client#createIndex
with the datatype
option set to Aerospike.indexDataType.BLOB
.
Options for creating the index.
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
var binName = 'location'
var indexName = 'locationIndex'
var options = { ns: 'test',
set: 'demo',
bin: binName,
index: indexName }
client.createBlobIndex(options, function (error) {
if (error) throw error
console.info('SI %s on %s was created successfully', indexName, binName)
client.close()
})
})
Options for creating the index.
The function to call when the command completes.
Options for creating the index.
The Info Policy to use for this command.
The function to call when the command completes.
Creates a geospatial secondary secondary index.
Options for creating the index.
Optional
policy: policy.InfoPolicyThe Info Policy to use for this command.
This is a short-hand for calling Client#createIndex
with the datatype
option set to Aerospike.indexDataType.GEO2DSPHERE
.
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
var binName = 'location'
var indexName = 'locationIndex'
var options = { ns: 'test',
set: 'demo',
bin: binName,
index: indexName }
client.createGeo2DSphereIndex(options, function (error) {
if (error) throw error
console.info('SI %s on %s was created successfully', indexName, binName)
client.close()
})
})
Options for creating the index.
The function to call when the command completes.
Options for creating the index.
The Info Policy to use for this command.
The function to call when the command completes.
Creates a secondary index (SI).
Options for creating the index.
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
A Promise that will resolve to an IndexJob instance.
Calling the createIndex
method issues an
index create command to the Aerospike cluster and returns immediately. To
verify that the index has been created and populated with all the data use
the IndexJob instance returned by the callback.
Aerospike currently supports indexing of strings, integers and geospatial information in GeoJSON format.
A string index allows for equality lookups. An equality lookup means that if you query for an indexed bin with value "abc", then only records containing bins with "abc" will be returned.
An integer index allows for either equality or range lookups. An equality lookup means that if you query for an indexed bin with value 123, then only records containing bins with the value 123 will be returned. A range lookup means that if you can query bins within a range. So, if your range is (1...100), then all records containing a value in that range will be returned.
A geo 2d sphere index allows either "contains" or "within" lookups. A "contains" lookup means that if you query for an indexed bin with GeoJSON point element, then only records containing bins with a GeoJSON element containing that point will be returned. A "within" lookup means that if you query for an indexed bin with a GeoJSON polygon element, then all records containing bins with a GeoJSON element wholly contained within that polygon will be returned.
const Aerospike = require('aerospike')
const Context = Aerospike.cdt.Context
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
// create index over user's recent locations
let namespace = 'test'
let set = 'demo'
let binName = 'rloc' // recent locations
let indexName = 'recentLocationsIdx'
let indexType = Aerospike.indexType.LIST
let dataType = Aerospike.indexDataType.GEO2DSPHERE
let context = new Context().addListIndex(0)
let options = { ns: namespace,
set: set,
bin: binName,
index: indexName,
type: indexType,
datatype: dataType,
context: context }
let policy = new Aerospike.InfoPolicy({ timeout: 100 })
client.createIndex(options, policy, (error, job) => {
if (error) throw error
// wait for index creation to complete
var pollInterval = 100
job.waitUntilDone(pollInterval, (error) => {
if (error) throw error
console.info('SI %s on %s was created successfully', indexName, binName)
client.close()
})
})
})
Options for creating the index.
The function to call when the command completes.
Options for creating the index.
The Info Policy to use for this command.
The function to call when the command completes.
Creates a SI of type Integer.
Options for creating the index.
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
This is a short-hand for calling Client#createIndex
with the datatype
option set to Aerospike.indexDataType.NUMERIC
.
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
var binName = 'age'
var indexName = 'ageIndex'
var options = { ns: 'test',
set: 'demo',
bin: binName,
index: indexName }
client.createIntegerIndex(options, function (error) {
if (error) throw error
console.info('SI %s on %s was created successfully', indexName, binName)
client.close()
})
})
Options for creating the index.
The function to call when the command completes.
Options for creating the index.
The Info Policy to use for this command.
The function to call when the command completes.
Create user defined role with optional privileges, whitelist and read/write quotas. Quotas require server security configuration "enable-quotas" to be set to true.
role name
List of privileges assigned to a role.
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
Optional
whitelist: null | string[]Optional list of allowable IP addresses assigned to role. IP addresses can contain wildcards (ie. 10.1.2.0/24).
Optional
readQuota: null | numberOptional maximum reads per second limit, pass in zero for no limit.
Optional
writeQuota: null | numberOptional maximum writes per second limit, pass in zero for no limit.
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configs can be used.
user: 'admin',
password: 'admin'
})
client.createRole("Engineer", [new Aerospike.admin.Privilege(Aerospike.privilegeCode.READ_WRITE), new Aerospike.admin.Privilege(Aerospike.privilegeCode.TRUNCATE)], null)
// Must wait a short length of time of the role to be fully created.
await wait(5)
const role = await client.queryRole("Engineer", null)
console.log(role)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
Creates a SI of type String.
Options for creating the index.
Optional
policy: policy.InfoPolicyThe Info Policy to use for this command.
This is a short-hand for calling Client#createIndex
with the datatype
option set to Aerospike.indexDataType.STRING
.
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
var binName = 'name'
var indexName = 'nameIndex'
var options = { ns: 'test',
set: 'demo',
bin: binName,
index: indexName }
client.createStringIndex(options, function (error) {
if (error) throw error
console.info('SI %s on %s was created successfully', indexName, binName)
client.close()
})
})
Options for creating the index.
The function to call when the command completes.
Options for creating the index.
The Info Policy to use for this command.
The function to call when the command completes.
Create user with password and roles. Clear-text password will be hashed using bcrypt before sending to server.
User name for the new user.
User password in clear-text format.
Optional
roles: null | string[]Optional array of role names. For more information on roles, see admin.Role.
Optional
policy: null | policy.AdminPolicyOptional policy.AdminPolicy.
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
client.createUser("khob", "MightyMice55!", ["Engineer"])
// Must wait a short length of time of the user to be fully created.
await wait(5)
const user = await client.queryUser("khob", null)
console.log(user)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
Disable extended periodic cluster and node latency metrics.
A Promise that resolves to void.
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
;(async () => {
let client = await Aerospike.connect(config)
await client.enableMetrics()
await client.disableMetrics()
await client.close()
})();
Disable extended periodic cluster and node latency metrics.
This function will be called with the result returned by the disableMetrics call.
Drop user defined role.
role name
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
// A role must be created before a role can be dropped. See {@link Client#createRole} for an example.
client.dropRole("Engineer")
// Must wait a short length of time of the role to be fully dropped.
await wait(5)
let roles = await client.queryRoles()
// 'Engineer' should no longer appear in the logged list of roles
console.log(roles)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
Remove a User from cluster
User name to be dropped.
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
// A user must be created before a user can be dropped. See {@link Client#createUser} for an example.
client.dropUser("khob")
// Must wait a short length of time of the role to be fully dropped.
await wait(5)
let users = await client.queryUsers()
// 'khob' should no longer appear in the logged list of roles
console.log(users)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
Synchronously calls each of the listeners registered for the event named eventName
, in the order they were registered, passing the supplied arguments
to each.
Returns true
if the event had listeners, false
otherwise.
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
Rest
...args: AnyRestEnable extended periodic cluster and node latency metrics.
A Promise that resolves to void.
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
;(async () => {
let client = await Aerospike.connect(config)
client.enableMetrics()
client.disableMetrics()
await client.close()
})();
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
function enableListener() {
console.log("Metrics Enabled")
return
}
function snapshotListener(cluster: Cluster) {
console.log(Cluster.clusterName)
return
}
function nodeCloseListener(node: Node) {
console.log(node.conns)
return
}
function disableListener(cluster: Cluster) {
console.log("Metrics Disabled")
return
}
;(async () => {
let client = await Aerospike.connect(config)
let listeners: MetricsListeners = new Aerospike.MetricsListeners({
enableListener,
disableListener,
nodeCloseListener,
snapshotListener
}
)
let policy: MetricsPolicy = new MetricsPolicy({
metricsListeners: listeners,
reportDir: metricsLogFolder,
reportSizeLimit: 1000,
interval: 2,
latencyColumns: 5,
latencyShift: 2
}
)
await client.enableMetrics(policy)
await client.disableMetrics()
// All listeners are fired asynchronously
// If you need the enableListener or disableListener to fire immediately, yield control of the event loop.
await new Promise(r => setTimeout(r, 0));
await client.close()
Enable extended periodic cluster and node latency metrics.
This function will be called with the result returned by the enableMetrics call.
Enable extended periodic cluster and node latency metrics.
policy.MetricsPolicy instance.
A Promise that resolves to void.
Enable extended periodic cluster and node latency metrics.
policy.MetricsPolicy instance.
This function will be called with the result returned by the abort function call.
Returns an array listing the events for which the emitter has registered
listeners. The values in the array are strings or Symbol
s.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
Checks the existance of a record in the database cluster.
The key of the record to check for existance.
Optional
policy: null | policy.ReadPolicyThe Read Policy to use for this command.
A Promise that resolves to true
if the record exists or
false
otherwise.
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
policies: {
read : new Aerospike.ReadPolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
let key = new Aerospike.Key('test', 'demo', 'key1')
Aerospike.connect(config)
.then(client => {
return client.exists(key)
.then(exists => console.info('Key "%s" exists: %s', key.key, exists))
.then(() => client.close())
.catch(error => {
console.error('Error checking existance of key:', error)
client.close()
})
})
.catch(error => {
console.error('Error connecting to cluster:', error)
})
The key of the record to check for existance.
The function to call when the
command completes; the passed value is true
if the record
exists or false
otherwise.
The key of the record to check for existance.
The Read Policy to use for this command.
The function to call when the
command completes; the passed value is true
if the record
exists or false
otherwise.
Checks the existance of a record in the database cluster.
The key of the record to check for existance.
Optional
policy: policy.ReadPolicyThe Read Policy to use for this command.
A Promise that resolves to an AerospikeRecord containing no bins and a RecordMetadata object. If the metadata contains data, the record exists. If the metadata contains null values, then the record does not exist.
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
policies: {
read : new Aerospike.ReadPolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
let key = new Aerospike.Key('test', 'demo', 'key1')
Aerospike.connect(config)
.then(client => {
return client.exists(key)
.then(exists => console.info('Key "%s" exists: %s', key.key, exists))
.then(() => client.close())
.catch(error => {
console.error('Error checking existance of key:', error)
client.close()
})
})
.catch(error => {
console.error('Error connecting to cluster:', error)
})
The key of the record to check for existance.
The function to call when the command completes; An AerospikeRecord will be passed to the callback, containing no bins and a RecordMetadata object. If the metadata contains data, the record exists. If the metadata contains null values, then the record does not exist.
The key of the record to check for existance.
The Read Policy to use for this command.
The function to call when the command completes; An AerospikeRecord will be passed to the callback, containing no bins and a RecordMetadata object. If the metadata contains data, the record exists. If the metadata contains null values, then the record does not exist.
Using the key provided, reads a record from the database cluster.
The key used to locate the record in the cluster.
Optional
policy: policy.ReadPolicyThe Read Policy to use for this command.
A Promise
that resolves to a Record.
const Aerospike = require('aerospike')
var key = new Aerospike.Key('test', 'demo', 'key1')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
policies: {
read : new Aerospike.ReadPolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
client.get(key, (error, record) => {
if (error) throw error
console.log(record)
client.close()
})
})
The key used to locate the record in the cluster.
The function to call when the
command completes with the results of the command; if no callback
function is provided, the method returns a Promise
instead.
Returns void
get(key, policy, callback): void
Parameters
key: KeyOptionsThe key used to locate the record in the cluster.
policy: policy.ReadPolicyThe Read Policy to use for this command.
callback: TypedCallback<AerospikeRecord>The function to call when the
command completes with the results of the command; if no callback
function is provided, the method returns a Promise instead.
Returns void
getMaxListeners
- get
MaxListeners (): number Returns the current max listener value for the EventEmitter
which is either
set by emitter.setMaxListeners(n)
or defaults to EventEmitter.defaultMaxListeners.
Returns number
getNodes
- get
Nodes (): Node[] Returns a list of all cluster nodes known to the client.
Returns Node[]
List of node objects
Example
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
console.log(client.getNodes()) // [ { name: 'SAMPLEADDRESS', address: 'SAMPLENAME' }, ...]
client.close()
})
grantPrivileges
- grant
Privileges (roleName, privileges, policy?): void Grant privileges to an user defined role.
Parameters
- roleName: string
role name
- privileges: Privilege[]
list of privileges assigned to a role.
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
Returns void
Example
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
// A role must be created before privileges can be granted. See {@link Client#createUser} for an example.
client.grantPrivileges("Engineer", [new Aerospike.admin.Privilege(Aerospike.privilegeCode.SINDEX_ADMIN)])
// Must wait a short length of time for the privilege to be granted.
await wait(5)
let role = await client.queryRole("Engineer")
console.log(role)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
grantRoles
- grant
Roles (user, roles, policy?): void Drop user defined role.
Parameters
- user: string
User name for granted roles
- roles: string[]
Optional array of role names. For more information on roles, see admin.Role.
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
Returns void
Example
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
// A user must be created before roles can be granted. See {@link Client#createUser} for an example.
client.grantRoles("khob", ["Engineer"])
// Must wait a short length of time for the role to be granted
await wait(5)
let user = await client.queryUser("khob")
console.log(user)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
incr
- incr(key, bins, metadata?, policy?): Promise<AerospikeRecord>
Alias for Client#add.
Parameters
- key: KeyOptions
The key of the record.
- bins: AerospikeBins
The key-value mapping of bin names and the corresponding values to use to increment the bin values with.
Optional
metadata: RecordMetadataMeta data.
Optional
policy: policy.OperatePolicyThe Operate Policy to use for this command.
Returns Promise<AerospikeRecord>
A Promise that resolves to the results of the opertion.
- incr(key, bins, callback): void
Alias for Client#add.
Parameters
- key: KeyOptions
The key of the record.
- bins: AerospikeBins
The key-value mapping of bin names and the corresponding values to use to increment the bin values with.
- callback: TypedCallback<AerospikeRecord>
The function to call when the
command completes with the results of the command.
Returns void
- incr(key, bins, metadata, callback): void
Alias for Client#add.
Parameters
- key: KeyOptions
The key of the record.
- bins: AerospikeBins
The key-value mapping of bin names and the corresponding values to use to increment the bin values with.
- metadata: null | RecordMetadata
Meta data.
- callback: TypedCallback<AerospikeRecord>
The function to call when the
command completes with the results of the command.
Returns void
- incr(key, bins, metadata, policy, callback): void
Alias for Client#add.
Parameters
- key: KeyOptions
The key of the record.
- bins: AerospikeBins
The key-value mapping of bin names and the corresponding values to use to increment the bin values with.
- metadata: null | RecordMetadata
Meta data.
- policy: null | policy.OperatePolicy
The Operate Policy to use for this command.
- callback: TypedCallback<AerospikeRecord>
The function to call when the
command completes with the results of the command.
Returns void
indexRemove
- index
Remove (namespace, index, policy?): Promise<void> Removes the specified index.
Parameters
- namespace: string
The namespace on which the index was created.
- index: string
The name of the index.
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
Returns Promise<void>
A Promise
that resolves once the command completes.
Example
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
client.indexRemove('location', 'locationIndex', (error) => {
if (error) throw error
client.close()
})
})
- index
Remove (namespace, index, callback): void Parameters
- namespace: string
The namespace on which the index was created.
- index: string
The name of the index.
- callback: TypedCallback<void>
The function to call when the
command completes with the result of the command.
Returns void
- index
Remove (namespace, index, policy, callback): void Parameters
- namespace: string
The namespace on which the index was created.
- index: string
The name of the index.
- policy: null | policy.InfoPolicy
The Info Policy to use for this k.
- callback: TypedCallback<void>
The function to call when the
command completes with the result of the command.
Returns void
info
- info(request, host, policy?): Promise<string>
Sends an info query to a specific cluster node.
Parameters
- request: string
The info request to send.
- host: string | Host
See Host. The address of the cluster host to send the request to.
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
Returns Promise<string>
A Promise
that resolves to an info result string.
Remarks
The request
parameter is a string representing an
info request. If it is not specified, a default set of info values will be
returned.
Please refer to the
Info Command Reference
for a list of all available info commands.
Deprecated
since v3.11.0 - use Client#infoNode or Client#infoAny instead.
Example: Sending a 'statistics' info query to a single host
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
client.info('statistics', {addr: '192.168.33.10', port: 3000}, (error, response) => {
if (error) throw error
console.log(response)
client.close()
})
})
- info(request, host, callback): void
Parameters
- request: undefined | string
The info request to send.
- host: string | Host
See Host. The address of the cluster host to send the request to.
- callback: TypedCallback<string>
The function to call when an info response from a cluster host is received.
Returns void
- info(request, host, policy, callback): void
Parameters
- request: undefined | string
The info request to send.
- host: string | Host
See Host. The address of the cluster host to send the request to.
- policy: null | policy.InfoPolicy
The Info Policy to use for this command.
- callback: TypedCallback<string>
The function to call when an info response from a cluster host is received.
Returns void
infoAll
- info
All (request?, policy?): Promise<InfoAllResponse[]> Sends an info query to all nodes in the cluster and collects the
results.
Parameters
Optional
request: stringThe info request to send.
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
Returns Promise<InfoAllResponse[]>
A Promise
that resolves to an InfoAllResponse.
Remarks
The request
parameter is a string representing an
info request. If it is not specified, a default set of info values will be
returned.
Example: Sending info command to whole cluster
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
Client.infoAll('statistics', (error, response) => {
if (error) throw error
console.log(response)
client.close()
})
})
- info
All (request?, callback?): void Parameters
Optional
request: stringThe info request to send.
Optional
callback: TypedCallback<InfoAllResponse[]>The function to call once all nodes have
returned a response to the info command; if no callback function is
provided, the method returns a Promise instead.
Returns void
infoAll (request?, policy?, callback?): void
Parameters
Optional
request: stringThe info request to send.
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
Optional
callback: TypedCallback<InfoAllResponse[]>The function to call once all nodes have
returned a response to the info command; if no callback function is
provided, the method returns a Promise instead.
Returns void
infoAny
- info
Any (request?, policy?): Promise<string> Sends an info query to a single, randomly selected cluster node.
Parameters
Optional
request: stringThe info request to send.
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
Returns Promise<string>
A Promise
that resolves to an info result string.
Remarks
The request
parameter is a string representing an
info request. If it is not specified, a default set of info values will be
returned.
Example: Sending 'statistics' info command to random cluster node
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
client.infoAny('statistics', (error, response) => {
if (error) throw error
console.log(response)
client.close()
})
})
- info
Any (callback): void Parameters
- callback: TypedCallback<string>
The function to call once the node
returns the response to the info command; if no callback function is
provided, the method returns a Promise instead.
Returns void
infoAny (request?, callback?): void
Parameters
Optional
request: stringThe info request to send.
Optional
callback: TypedCallback<string>The function to call once the node
returns the response to the info command; if no callback function is
provided, the method returns a Promise instead.
Returns void
infoAny (request?, policy?, callback?): void
Parameters
Optional
request: stringThe info request to send.
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
Optional
callback: TypedCallback<string>The function to call once the node
returns the response to the info command; if no callback function is
provided, the method returns a Promise instead.
Returns void
infoNode
- info
Node (request, node, policy?): Promise<string> Sends an info query to a single node in the cluster.
Parameters
- request: undefined | string
The info request to send.
- node: InfoNodeParam
The node to send the request to. See InfoNodeParam.
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
Returns Promise<string>
A Promise
that resolves to an info result string.
Remarks
The request
parameter is a string representing an
info request. If it is not specified, a default set of info values will be
returned.
Example: Sending 'statistics' info command to specific cluster node
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
const node = client.getNodes().pop()
client.infoNode('statistics', node, (error, response) => {
if (error) throw error
console.log(response)
client.close()
})
})
- info
Node (request, node, callback): void Parameters
- request: undefined | string
The info request to send.
- node: InfoNodeParam
The node to send the request to. See InfoNodeParam.
- callback: TypedCallback<string>
The function to call once the node
returns the response to the info command; if no callback function is
provided, the method returns a Promise instead.
Returns void
infoNode (request, node, policy, callback): void
Parameters
request: undefined | stringThe info request to send.
node: InfoNodeParamThe node to send the request to. See InfoNodeParam.
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
callback: TypedCallback<string>The function to call once the node
returns the response to the info command; if no callback function is
provided, the method returns a Promise instead.
Returns void
isConnected
- is
Connected (checkTenderErrors?): boolean Is client connected to any server nodes.
Parameters
Optional
checkTenderErrors: booleanWhether to consider a server
node connection that has had 5 consecutive info request failures during
cluster tender. Default is true.
Returns boolean
true
if the client is currently connected to any server nodes.
listenerCount
- listener
Count <K>(eventName, listener?): number Returns the number of listeners listening for the event named eventName
.
If listener
is provided, it will return how many times the listener is found
in the list of the listeners of the event.
Type Parameters
Parameters
- eventName: string | symbol
The name of the event being listened for
Optional
listener: FunctionThe event handler function
Returns number
listeners
- listeners<K>(eventName): Function[]
Returns a copy of the array of listeners for the event named eventName
.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
Type Parameters
Parameters
- eventName: string | symbol
Returns Function[]
off
- off<K>(eventName, listener): this
Alias for emitter.removeListener()
.
Type Parameters
Parameters
- eventName: string | symbol
- listener: ((...args: any[]) => void)
- (...args): void
Parameters
Rest
...args: any[]
Returns void
Returns this
on
- on<K>(eventName, listener): this
Adds the listener
function to the end of the listeners array for the event
named eventName
. No checks are made to see if the listener
has already
been added. Multiple calls passing the same combination of eventName
and
listener
will result in the listener
being added, and called, multiple times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter
, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependListener()
method can be used as an alternative to add the
event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
Type Parameters
Parameters
- eventName: string | symbol
The name of the event.
- listener: ((...args: any[]) => void)
The callback function
- (...args): void
Parameters
Rest
...args: any[]
Returns void
Returns this
once
- once<K>(eventName, listener): this
Adds a one-time listener
function for the event named eventName
. The
next time eventName
is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter
, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener()
method can be used as an alternative to add the
event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
Type Parameters
Parameters
- eventName: string | symbol
The name of the event.
- listener: ((...args: any[]) => void)
The callback function
- (...args): void
Parameters
Rest
...args: any[]
Returns void
Returns this
operate
- operate(key, operations, metadata?, policy?): Promise<AerospikeRecord>
Performs multiple operations on a single record.
Parameters
- key: KeyOptions
The key of the record.
- operations: Operation[]
List of Operations to perform on the record.
Optional
metadata: null | RecordMetadataMeta data.
Optional
policy: null | policy.OperatePolicyThe Operate Policy to use for this command.
Returns Promise<AerospikeRecord>
Example
const Aerospike = require('aerospike')
const op = Aerospike.operations
const key = new Aerospike.Key('test', 'demo', 'mykey1')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
operate : new Aerospike.OperatePolicy({socketTimeout : 0, totalTimeout : 0}),
write : new Aerospike.WritePolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
var ops = [
op.append('a', 'xyz'),
op.incr('b', 10),
op.read('b')
]
Aerospike.connect(config, (error, client) => {
if (error) throw error
client.put(key, { a: 'abc', b: 42 }, (error) => {
if (error) throw error
client.operate(key, ops, (error, record) => {
if (error) throw error
console.log(record.bins) // => { b: 52 }
client.close()
})
})
})
- operate(key, operations, callback): void
Parameters
- key: KeyOptions
The key of the record.
- operations: Operation[]
List of Operations to perform on the record.
- callback: TypedCallback<AerospikeRecord>
The function to call when the
command completes with the results of the command; if no callback
function is provided, the method returns a Promise instead.
Returns void
operate(key, operations, metadata, callback): void
Parameters
key: KeyOptionsThe key of the record.
operations: Operation[]List of Operations to perform on the record.
metadata: RecordMetadataMeta data.
callback: TypedCallback<AerospikeRecord>The function to call when the
command completes with the results of the command; if no callback
function is provided, the method returns a Promise instead.
Returns void
operate(key, operations, metadata, policy, callback): void
Parameters
key: KeyOptionsThe key of the record.
operations: Operation[]List of Operations to perform on the record.
metadata: null | RecordMetadataMeta data.
policy: null | policy.OperatePolicyThe Operate Policy to use for this command.
callback: TypedCallback<AerospikeRecord>The function to call when the
command completes with the results of the command; if no callback
function is provided, the method returns a Promise instead.
Returns void
prepend
- prepend(key, bins, metadata?, policy?): Promise<AerospikeRecord>
Shortcut for applying the operations.prepend operation to one or more record bins.
Parameters
- key: KeyOptions
The key of the record.
- bins: AerospikeBins
The key-value mapping of bin names and the corresponding values to prepend to the bin value.
Optional
metadata: null | RecordMetadataMeta data.
Optional
policy: null | policy.OperatePolicyThe Operate Policy to use for this command.
Returns Promise<AerospikeRecord>
A Promise that resolves to the results of the opertion.
- prepend(key, bins, callback): void
Parameters
- key: KeyOptions
The key of the record.
- bins: AerospikeBins
The key-value mapping of bin names and the corresponding values to prepend to the bin value.
- callback: TypedCallback<AerospikeRecord>
The function to call when the
command completes with the results of the command.
Returns void
- prepend(key, bins, metadata, callback): void
Parameters
- key: KeyOptions
The key of the record.
- bins: AerospikeBins
The key-value mapping of bin names and the corresponding values to prepend to the bin value.
- metadata: null | RecordMetadata
Meta data.
- callback: TypedCallback<AerospikeRecord>
The function to call when the
command completes with the results of the command.
Returns void
- prepend(key, bins, metadata, policy, callback): void
Parameters
- key: KeyOptions
The key of the record.
- bins: AerospikeBins
The key-value mapping of bin names and the corresponding values to prepend to the bin value.
- metadata: null | RecordMetadata
Meta data.
- policy: null | policy.OperatePolicy
The Operate Policy to use for this command.
- callback: TypedCallback<AerospikeRecord>
The function to call when the
command completes with the results of the command.
Returns void
prependListener
- prepend
Listener <K>(eventName, listener): this Adds the listener
function to the beginning of the listeners array for the
event named eventName
. No checks are made to see if the listener
has
already been added. Multiple calls passing the same combination of eventName
and listener
will result in the listener
being added, and called, multiple times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the EventEmitter
, so that calls can be chained.
Type Parameters
Parameters
- eventName: string | symbol
The name of the event.
- listener: ((...args: any[]) => void)
The callback function
- (...args): void
Parameters
Rest
...args: any[]
Returns void
Returns this
prependOnceListener
- prepend
OnceListener <K>(eventName, listener): this Adds a one-timelistener
function for the event named eventName
to the beginning of the listeners array. The next time eventName
is triggered, this
listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter
, so that calls can be chained.
Type Parameters
Parameters
- eventName: string | symbol
The name of the event.
- listener: ((...args: any[]) => void)
The callback function
- (...args): void
Parameters
Rest
...args: any[]
Returns void
Returns this
put
- put(key, bins, meta?, policy?): Promise<Key>
Writes a record to the database cluster.
Parameters
- key: KeyOptions
The key of the record.
- bins:
| AerospikeBins
| AerospikeRecord
| Bin
| Map<string, AerospikeBinValue>A record object used for specifying the fields to store.
Optional
meta: null | RecordMetadataMeta data.
Optional
policy: null | policy.WritePolicyThe Write Policy to use for this command.
Returns Promise<Key>
A Promise
that resolves to a Record.
Remarks
If the record exists, it modifies the record with bins provided.
To remove a bin, set its value to null
.
Note: The client does not perform any automatic data type conversions.
Attempting to write an unsupported data type (e.g. boolean) into a record
bin will cause an error to be returned. Setting an undefined
value will also cause an error.
Example
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
read : new Aerospike.ReadPolicy({socketTimeout : 0, totalTimeout : 0}),
write : new Aerospike.WritePolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
const Key = Aerospike.Key
var key = new Key('test', 'demo', 'key1')
var bins = {
a: 'xyz',
b: 123
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
client.put(key, bins, (error) => {
if (error) throw error
client.get(key, (error, record) => {
if (error) throw error
console.log(record)
client.close()
})
})
})
- put(key, bins, callback): void
Parameters
- key: KeyOptions
The key of the record.
- bins:
| AerospikeBins
| AerospikeRecord
| Bin
| Map<string, AerospikeBinValue>A record object used for specifying the fields to store.
- callback: TypedCallback<Key>
The function to call when the command completes with the result of the command.
Returns void
- put(key, bins, meta, callback): void
Parameters
- key: KeyOptions
The key of the record.
- bins:
| AerospikeBins
| AerospikeRecord
| Bin
| Map<string, AerospikeBinValue>A record object used for specifying the fields to store.
- meta: null | RecordMetadata
Meta data.
- callback: TypedCallback<Key>
The function to call when the command completes with the result of the command.
Returns void
- put(key, bins, meta, policy, callback): void
Parameters
- key: KeyOptions
The key of the record.
- bins:
| AerospikeBins
| AerospikeRecord
| Bin
| Map<string, AerospikeBinValue>A record object used for specifying the fields to store.
- meta: null | RecordMetadata
Meta data.
- policy: null | policy.WritePolicy
The Write Policy to use for this command.
- callback: TypedCallback<Key>
The function to call when the command completes with the result of the command.
Returns void
query
- query(ns, options?): Query
Creates a new Query instance, which is used to define query
in the database.
Parameters
- ns: string
The namespace to be queried.
Optional
options: QueryOptionsQuery parameters. See Query constructor for details.
Returns Query
A Promise
that resolves to a Query.
- query(ns, set, options?): Query
Parameters
- ns: string
The namespace to be queried.
- set: null | string
The set on which the query is to be executed.
Optional
options: QueryOptionsQuery parameters. See Query constructor for details.
Returns Query
queryRole
- query
Role (roleName, policy?): Role Retrieves an admin.Role from the database.
Parameters
- roleName: string
role name filter.
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
Returns Role
An instance of admin.Role. For more information on roles, see admin.Role.
Example
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
// A role must be created before a role can be queried. See {@link Client#createRole} for an example.
let role = await client.queryRole("Engineer")
console.log(role)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
queryRoles
- query
Roles (policy?): Role[] Retrieve all roles and role information from the database.
Parameters
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
Returns Role[]
An list of admin.Role instances. For more information on roles, see admin.Role.
Example
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
let roles = await client.queryRoles()
console.log(roles)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
queryUser
- query
User (user, policy?): User Retrieves an admin.User from the database.
Parameters
- user: string
User name filter.
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
Returns User
An instance of admin.User. For more information on roles, see admin.User.
Example
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
// A user must be created before a user can be queried. See {@link Client#createUser} for an example.
let user = await client.queryUser("khob")
console.log(user)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
queryUsers
- query
Users (policy?): User[] Retrieves All user and user information from the database.
Parameters
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
Returns User[]
An list of admin.User instances. For more information on roles, see admin.User.
Example
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
let users = await client.queryUsers()
console.log(users)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
rawListeners
- raw
Listeners <K>(eventName): Function[] Returns a copy of the array of listeners for the event named eventName
,
including any wrappers (such as those created by .once()
).
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
Type Parameters
Parameters
- eventName: string | symbol
Returns Function[]
remove
- remove(key, policy?): Promise<Key>
Removes a record with the specified key from the database cluster.
Parameters
- key: KeyOptions
The key of the record.
Optional
policy: null | policy.RemovePolicyThe Remove Policy to use for this command.
Returns Promise<Key>
A Promise
that resolves to the Key of the removed record.
Example
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
remove : new Aerospike.RemovePolicy({socketTimeout : 0, totalTimeout : 0}),
write : new Aerospike.WritePolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
const Key = Aerospike.Key
var key = new Key('test', 'demo', 'key1')
var bins = {
a: 'xyz',
b: 123
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
client.put(key, bins, (error) => {
if (error) throw error
client.remove(key, (error) => {
if (error) throw error
console.log("Record removed")
client.close()
})
})
})
- remove(key, callback): void
Parameters
- key: KeyOptions
The key of the record.
- callback: TypedCallback<Key>
The function to call when the command completes with the results of the command.
Returns void
- remove(key, policy, callback): void
Parameters
- key: KeyOptions
The key of the record.
- policy: null | policy.RemovePolicy
The Remove Policy to use for this command.
- callback: TypedCallback<Key>
The function to call when the command completes with the results of the command.
Returns void
removeAllListeners
- remove
AllListeners (eventName?): this Removes all listeners, or those of the specified eventName
.
It is bad practice to remove listeners added elsewhere in the code,
particularly when the EventEmitter
instance was created by some other
component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter
, so that calls can be chained.
Parameters
Optional
eventName: string | symbol
Returns this
removeListener
- remove
Listener <K>(eventName, listener): this Removes the specified listener
from the listener array for the event named eventName
.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
removeListener()
will remove, at most, one instance of a listener from the
listener array. If any single listener has been added multiple times to the
listener array for the specified eventName
, then removeListener()
must be
called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
time of emitting are called in order. This implies that any removeListener()
or removeAllListeners()
calls after emitting and before the last listener finishes execution
will not remove them fromemit()
in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
Because listeners are managed using an internal array, calling this will
change the position indices of any listener registered after the listener
being removed. This will not impact the order in which listeners are called,
but it means that any copies of the listener array as returned by
the emitter.listeners()
method will need to be recreated.
When a single function has been added as a handler multiple times for a single
event (as in the example below), removeListener()
will remove the most
recently added instance. In the example the once('ping')
listener is removed:
import { EventEmitter } from 'node:events';
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
Returns a reference to the EventEmitter
, so that calls can be chained.
Type Parameters
Parameters
- eventName: string | symbol
- listener: ((...args: any[]) => void)
- (...args): void
Parameters
Rest
...args: any[]
Returns void
Returns this
removeSeedHost
- remove
SeedHost (hostname, port?): void Removes a seed host from the cluster.
Parameters
- hostname: string
Hostname/IP address of the seed host
Optional
port: numberPort number; defaults to Config#port or 3000.
Returns void
revokePrivileges
- revoke
Privileges (roleName, privileges, policy?): void Revoke privileges from an user defined role.
Parameters
- roleName: string
role name
- privileges: Privilege[]
List of privileges assigned to a role.
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
Returns void
Example
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
// A role must be created before privileges can be revoked. See {@link Client#createRole} for an example.
client.revokePrivileges("Engineer", [new Aerospike.admin.Privilege(Aerospike.privilegeCode.SINDEX_ADMIN)])
// Must wait a short length of time for the privilege to be granted.
await wait(5)
let users = await client.queryRole("Engineer")
console.log(users)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
revokeRoles
- revoke
Roles (user, roles, policy?): void Remove roles from user's list of roles.
Parameters
- user: string
User name for revoked roles.
- roles: string[]
Optional array of role names. For more information on roles, see admin.Role.
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
Returns void
Example
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
// A user must be created before roles can be revoked. See {@link Client#createUser} for an example.
client.revokeRoles("khob", ["Engineer"])
// Must wait a short length of time for the privilege to be granted.
await wait(5)
let user = await client.queryUser("khob")
console.log(user)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
scan
- scan(ns, options?): Scan
Creates a new Scan instance in order to execute a database
scan using the Scan API.
Parameters
- ns: string
The namescape.
Optional
options: ScanOptionsScan parameters. See Scan constructor for details.
Returns Scan
A Promise
that resolves to a Query.
See
Scan constructor for options that can be used to initialize a
new instance.
- scan(ns, set?, options?): Scan
Parameters
- ns: string
The namescape.
Optional
set: stringThe name of a set.
Optional
options: ScanOptionsScan parameters. See Scan constructor for details.
Returns Scan
A Promise
that resolves to a Query.
select
- select(key, bins, policy?): Promise<AerospikeRecord>
Retrieves selected bins for a record of given key from the database cluster.
Parameters
- key: KeyOptions
The key of the record.
- bins: string[]
A list of bin names for the bins to be returned.
Optional
policy: null | policy.ReadPolicyThe Read Policy to use for this command.
Returns Promise<AerospikeRecord>
A Promise
that resolves to a AerospikeRecord.
Example
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
// Timeouts disabled, latency dependent on server location. Configure as needed.
policies: {
read : new Aerospike.ReadPolicy({socketTimeout : 0, totalTimeout : 0}),
write : new Aerospike.WritePolicy({socketTimeout : 0, totalTimeout : 0}),
}
}
const Key = Aerospike.Key
var key = new Key('test', 'demo', 'key1')
var bins = {
a: 'xyz',
b: 123
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
client.put(key, bins, (error) => {
if (error) throw error
client.select(key, ['a', 'b'], (error, record) => {
if (error) throw error
console.log(record)
client.close()
})
})
})
- select(key, bins, callback): void
Parameters
- key: KeyOptions
The key of the record.
- bins: string[]
A list of bin names for the bins to be returned.
- callback: TypedCallback<AerospikeRecord>
The function to call when the
command completes with the results of the command; if no callback
function is provided, the method returns a Promise instead.
Returns void
select(key, bins, policy, callback): void
Parameters
key: KeyOptionsThe key of the record.
bins: string[]A list of bin names for the bins to be returned.
policy: null | policy.ReadPolicyThe Read Policy to use for this command.
callback: TypedCallback<AerospikeRecord>The function to call when the
command completes with the results of the command; if no callback
function is provided, the method returns a Promise instead.
Returns void
setMaxListeners
- set
MaxListeners (n): this By default EventEmitter
s will print a warning if more than 10
listeners are
added for a particular event. This is a useful default that helps finding
memory leaks. The emitter.setMaxListeners()
method allows the limit to be
modified for this specific EventEmitter
instance. The value can be set to Infinity
(or 0
) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter
, so that calls can be chained.
Parameters
- n: number
Returns this
setQuotas
- set
Quotas (roleName, readQuota, writeQuota, policy?): void Set maximum reads/writes per second limits for a role. If a quota is zero, the limit is removed.
Quotas require server security configuration "enable-quotas" to be set to true.
Parameters
- roleName: string
role name
- readQuota: number
maximum reads per second limit, pass in zero for no limit.
- writeQuota: number
maximum writes per second limit, pass in zero for no limit.
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
Returns void
Example
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
// Quotas must be enabled in the server configurations for quotas to be set.
client.setQuotas("Engineer", 200, 300)
// Must wait a short length of time for the privilegee to be granted.
await wait(5)
let role = await client.queryRole("Engineer")
console.log(role)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
setWhitelist
- set
Whitelist (roleName, whitelist, policy?): void Set IP address whitelist for a role. If whitelist is null or empty, remove existing whitelist from role.
Parameters
- roleName: string
role name
- whitelist: null | string[]
Optional list of allowable IP addresses assigned to role.
IP addresses can contain wildcards (ie. 10.1.2.0/24).
Optional
policy: null | policy.AdminPolicyOptional AdminPolicy.
Returns void
Example
const Aerospike = require('aerospike')
function wait (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
;(async function () {
let client
try {
client = await Aerospike.connect({
hosts: '192.168.33.10:3000',
policies: {
write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
},
// Must have security enabled in server configuration before user and password configurations can be used.
user: 'admin',
password: 'admin'
})
// Quotas must be enabled in the server configurations for quotas to be set.
client.setWhitelist("Engineer", ["172.17.0.2"])
// Must wait a short length of time for the privilegee to be granted.
await wait(5)
let role = await client.queryRole("Engineer")
console.log(role)
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})()
stats
- stats(): Stats
Returns runtime stats about the client instance.
Returns Stats
Example
const Aerospike = require('aerospike')
// INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
var config = {
hosts: '192.168.33.10:3000',
}
Aerospike.connect(config, (error, client) => {
if (error) throw error
const stats = client.stats()
console.info(stats) // => { commands: { inFlight: 0, queued: 0 },
// nodes:
// [ { name: 'BB94DC08D270008',
// syncConnections: { inPool: 1, inUse: 0 },
// asyncConnections: { inPool: 0, inUse: 0 } },
// { name: 'C1D4DC08D270008',
// syncConnections: { inPool: 0, inUse: 0 },
// asyncConnections: { inPool: 0, inUse: 0 } } ] }
client.close()
})
truncate
- truncate(ns, set, beforeNanos, policy?): Promise<void>
Removes records in specified namespace/set efficiently.
Parameters
- ns: string
Required namespace.
- set: null | string
Optional set name. Set to null
to delete
all sets in namespace.
- beforeNanos: number
Optionally delete records before given last
update time. Units are in nanoseconds since unix epoch (1970-01-01). If
specified, the value must be before the current time. Pass in 0 to delete
all records in namespace/set regardless of last udpate time.
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
Returns Promise<void>
A Promise
that resolves when the truncate is complete.
- truncate(ns, callback): void
Parameters
- ns: string
Required namespace.
- callback: TypedCallback<void>
Returns void
- truncate(ns, set, callback): void
Parameters
- ns: string
Required namespace.
- set: null | string
Optional set name. Set to null
to delete
all sets in namespace.
- callback: TypedCallback<void>
Returns void
- truncate(ns, set, beforeNanos, callback): void
Parameters
- ns: string
Required namespace.
- set: null | string
Optional set name. Set to null
to delete
all sets in namespace.
- beforeNanos: number
Optionally delete records before given last
update time. Units are in nanoseconds since unix epoch (1970-01-01). If
specified, the value must be before the current time. Pass in 0 to delete
all records in namespace/set regardless of last udpate time.
- callback: TypedCallback<void>
Returns void
- truncate(ns, set, beforeNanos, policy, callback): void
Parameters
- ns: string
Required namespace.
- set: null | string
Optional set name. Set to null
to delete
all sets in namespace.
- beforeNanos: number
Optionally delete records before given last
update time. Units are in nanoseconds since unix epoch (1970-01-01). If
specified, the value must be before the current time. Pass in 0 to delete
all records in namespace/set regardless of last udpate time.
- policy: null | policy.InfoPolicy
The Info Policy to use for this command.
- callback: TypedCallback<void>
Returns void
udfRegister
- udf
Register (udfPath, udfType?, policy?): Promise<Job<JobInfoResponse>> Registers a UDF module with the database cluster.
Parameters
- udfPath: string
The file path to the Lua script to load into the server.
Optional
udfType: null | LUALanguage of the UDF script. Lua is the default
and only supported scripting language for UDF modules at the moment; ref.
language.
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
Returns Promise<Job<JobInfoResponse>>
A Promise that resolves to a Job instance.
Remarks
This method loads a Lua script from the local filesystem into
the Aerospike database cluster and registers it for use as a UDF module. The
client uploads the module to a single cluster node. It then gets distributed
within the whole cluster automatically. The callback function is called once
the initial upload into the cluster has completed (or if an error occurred
during the upload). One of the callback parameters is a UdfJob
instance that can be used to verify that the module has been registered
successfully on the entire cluster.
Example
const Aerospike = require('aerospike')
Aerospike.connect((error, client) => {
if (error) throw error
var path = './udf/my_module.lua'
client.udfRegister(path, (error, job) => {
if (error) throw error
job.waitUntilDone(100, (error) => {
if (error) throw error
// UDF module was successfully registered on all cluster nodes
client.close()
})
})
})
- udf
Register (udfPath, policy?): Promise<Job<JobInfoResponse>> Parameters
- udfPath: string
The file path to the Lua script to load into the server.
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
Returns Promise<Job<JobInfoResponse>>
A Promise that resolves to a Job instance.
- udf
Register (udfPath, callback): void Parameters
- udfPath: string
The file path to the Lua script to load into the server.
- callback: TypedCallback<Job<JobInfoResponse>>
The function to call when the
command completes with the result of the command.
Returns void
- udf
Register (udfPath, udfType, callback): void Parameters
- udfPath: string
The file path to the Lua script to load into the server.
- udfType: null | LUA
Language of the UDF script. Lua is the default
and only supported scripting language for UDF modules at the moment; ref.
language.
- callback: TypedCallback<Job<JobInfoResponse>>
The function to call when the
command completes with the result of the command.
Returns void
- udf
Register (udfPath, policy, callback): void Parameters
- udfPath: string
The file path to the Lua script to load into the server.
- policy: null | policy.InfoPolicy
The Info Policy to use for this command.
- callback: TypedCallback<Job<JobInfoResponse>>
The function to call when the
command completes with the result of the command.
Returns void
- udf
Register (udfPath, udfType, policy, callback): void Parameters
- udfPath: string
The file path to the Lua script to load into the server.
- udfType: null | LUA
Language of the UDF script. Lua is the default
and only supported scripting language for UDF modules at the moment; ref.
language.
- policy: null | policy.InfoPolicy
The Info Policy to use for this command.
- callback: TypedCallback<Job<JobInfoResponse>>
The function to call when the
command completes with the result of the command.
Returns void
udfRemove
- udf
Remove (udfModule, policy?): Promise<Job<JobInfoResponse>> Removes a UDF module from the cluster.
Parameters
- udfModule: string
The basename of the UDF module, without the
local pathname but including the file extension (".lua").
Optional
policy: null | policy.InfoPolicyThe Info Policy to use for this command.
Returns Promise<Job<JobInfoResponse>>
Remarks
The info command to deregister the UDF module is sent to a
single cluster node by the client. It then gets distributed within the whole
cluster automatically. The callback function is called once the initial info
command has succeeded (or if an error occurred). One of the callback
parameters is a UdfJob instance that can be used to verify that the
module has been removed successfully from the entire cluster.
For server versions 4.5.0 and before, trying to delete an UDF module that
does not exist on the server, will return an error. Starting with server
version 4.5.1, the server no longer returns an error and the command will
succeed.
Example
const Aerospike = require('aerospike')
Aerospike.connect((error, client) => {
if (error) throw error
var module = 'my_module.lua'
client.udfRemove(module, (error, job) => {
if (error) throw error
job.waitUntilDone(100, (error) => {
if (error) throw error
// UDF module was successfully removed from all cluster nodes
client.close()
})
})
})
- udf
Remove (udfModule, callback): void Parameters
- udfModule: string
The basename of the UDF module, without the
local pathname but including the file extension (".lua").
- callback: TypedCallback<Job<JobInfoResponse>>
The function to call when the
command completes with the result of the command.
Returns void
- udf
Remove (udfModule, policy, callback): void Parameters
- udfModule: string
The basename of the UDF module, without the
local pathname but including the file extension (".lua").
- policy: policy.InfoPolicy
The Info Policy to use for this command.
- callback: TypedCallback<Job<JobInfoResponse>>
The function to call when the
command completes with the result of the command.
Returns void
updateLogging
- update
Logging (logConfig): void Updates log settings for the client.
Parameters
- logConfig: Log
Returns void
Static
addAbortListener
- add
AbortListener (signal, resource): Disposable Experimental
Listens once to the abort
event on the provided signal
.
Listening to the abort
event on abort signals is unsafe and may
lead to resource leaks since another third party with the signal can
call e.stopImmediatePropagation()
. Unfortunately Node.js cannot change
this since it would violate the web standard. Additionally, the original
API makes it easy to forget to remove listeners.
This API allows safely using AbortSignal
s in Node.js APIs by solving these
two issues by listening to the event such that stopImmediatePropagation
does
not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
Parameters
- signal: AbortSignal
- resource: ((event: Event) => void)
- (event): void
Parameters
- event: Event
Returns void
Returns Disposable
Disposable that removes the abort
listener.
Static
getEventListeners
- get
EventListeners (emitter, name): Function[] Returns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
the emitter.
For EventTarget
s this is the only way to get the event listeners for the
event target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
Parameters
- emitter: EventEmitter<DefaultEventMap> | EventTarget
- name: string | symbol
Returns Function[]
Static
getMaxListeners
- get
MaxListeners (emitter): number Returns the currently set max amount of listeners.
For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
the emitter.
For EventTarget
s this is the only way to get the max event listeners for the
event target. If the number of event handlers on a single EventTarget exceeds
the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
Parameters
- emitter: EventEmitter<DefaultEventMap> | EventTarget
Returns number
Static
listenerCount
- listener
Count (emitter, eventName): number A class method that returns the number of listeners for the given eventName
registered on the given emitter
.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
Parameters
- emitter: EventEmitter<DefaultEventMap>
The emitter to query
- eventName: string | symbol
The event name
Returns number
Static
on
- on(emitter, eventName, options?): AsyncIterator<any[], any, any>
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
Returns an AsyncIterator
that iterates eventName
events. It will throw
if the EventEmitter
emits 'error'
. It removes all listeners when
exiting the loop. The value
returned by each iteration is an array
composed of the emitted event arguments.
An AbortSignal
can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
Use the close
option to specify an array of event names that will end the iteration:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted
console.log('done'); // prints 'done'
Parameters
- emitter: EventEmitter<DefaultEventMap>
- eventName: string | symbol
Optional
options: StaticEventEmitterIteratorOptions
Returns AsyncIterator<any[], any, any>
An AsyncIterator
that iterates eventName
events emitted by the emitter
- on(emitter, eventName, options?): AsyncIterator<any[], any, any>
Parameters
- emitter: EventTarget
- eventName: string
Optional
options: StaticEventEmitterIteratorOptions
Returns AsyncIterator<any[], any, any>
Static
once
- once(emitter, eventName, options?): Promise<any[]>
Creates a Promise
that is fulfilled when the EventEmitter
emits the given
event or that is rejected if the EventEmitter
emits 'error'
while waiting.
The Promise
will resolve with an array of all the arguments emitted to the
given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error'
event
semantics and does not listen to the 'error'
event.
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
The special handling of the 'error'
event is only used when events.once()
is used to wait for another event. If events.once()
is used to wait for the
'error'
event itself, then it is treated as any other kind of event without
special handling:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
An AbortSignal
can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
Parameters
- emitter: EventEmitter<DefaultEventMap>
- eventName: string | symbol
Optional
options: StaticEventEmitterOptions
Returns Promise<any[]>
- once(emitter, eventName, options?): Promise<any[]>
Parameters
- emitter: EventTarget
- eventName: string
Optional
options: StaticEventEmitterOptions
Returns Promise<any[]>
Static
setMaxListeners
- set
MaxListeners (n?, ...eventTargets): void import { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
Parameters
Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, n
is set as the default max for all newly created {EventTarget} and {EventEmitter}
objects.
Returns void
The Aerospike Node.js client enables you to build an application in Node.js or Typescript with an Aerospike cluster as its database. The client manages the connections to the cluster and handles the commands performed against it.