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.
StaticcaptureValue: boolean
Change the default captureRejections option on all new EventEmitter objects.
Static ReadonlycaptureValue: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler.
StaticdefaultBy 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 ReadonlyerrorThis 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.
Optionalmetadata: null | RecordMetadataMeta data.
Optionalpolicy: 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
Optionalport: 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.
Optionalmetadata: null | RecordMetadataMeta data.
Optionalpolicy: 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.
Optionalpolicy: 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.
OptionalbatchPolicy: null | policy.BatchPolicyThe Batch Policy to use for this command.
OptionalbatchApplyPolicy: 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.
Optionalcallback: TypedCallback<BatchResult<B>[]>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.
OptionalbatchPolicy: policy.BatchPolicyThe Batch Policy to use for this command.
Optionalcallback: TypedCallback<BatchResult<B>[]>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.
OptionalbatchPolicy: policy.BatchPolicyThe Batch Policy to use for this command.
OptionalbatchApplyPolicy: policy.BatchApplyPolicyUDF policy configuration parameters.
Optionalcallback: TypedCallback<BatchResult<B>[]>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.
Optionalpolicy: 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.
Optionalpolicy: 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.
Optionalpolicy: 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.
Optionalcallback: TypedCallback<BatchResult<B>[]>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.
Optionalpolicy: null | policy.BatchPolicyThe Batch Policy to use for this command.
Optionalcallback: TypedCallback<BatchResult<B>[]>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.
OptionalbatchPolicy: null | policy.BatchPolicyThe Batch Policy to use for this command.
OptionalbatchRemovePolicy: 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.
Optionalcallback: TypedCallback<BatchResult<B>[]>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.
OptionalbatchPolicy: null | policy.BatchPolicyThe Batch Policy to use for this command.
Optionalcallback: TypedCallback<BatchResult<B>[]>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.
OptionalbatchPolicy: null | policy.BatchPolicyThe Batch Policy to use for this command.
OptionalbatchRemovePolicy: null | policy.BatchRemovePolicyRemove policy configuration parameters.
Optionalcallback: TypedCallback<BatchResult<B>[]>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.
Optionalpolicy: 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.
Optionalpolicy: 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.
Optionalcallback: TypedCallback<BatchResult<B>[]>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.
Optionalpolicy: policy.BatchPolicyThe Batch Policy to use for this command.
Optionalcallback: TypedCallback<BatchResult<B>[]>The function to call when the command completes, Includes the results of the batched command.
Client#changePassword
Change user's password by user. Clear-text password will be hashed using bcrypt before sending to server.
User name for the password change.
User password in clear-text format.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise that resolves to void upon success.
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: 'common_user',
password: 'example_password'
})
// User must be created before password is changed. See {@link Client#createUser} for an example.
await client.changePassword("khob", "TryTiger7!", ["Engineer"])
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})() User name for the password change.
User password in clear-text format.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
User name for the password change.
User password in clear-text format.
Optional AdminPolicy.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
Closes the client connection to the cluster.
OptionalreleaseEventLoop: 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.
Optionalcallback: 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 an index on blob data.
This is a short-hand for calling Client#createIndex with the datatype option set to Aerospike.indexDataType.BLOB.
Options for creating the index.
Optionalpolicy: 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 an expression index on blob data.
This is a short-hand for calling Client#createIndex with the datatype option set to Aerospike.indexDataType.BLOB.
Options for creating the index.
Optionalpolicy: 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 exp = Aerospike.exp.binBlob(binName)
var indexName = 'locationIndex'
var options = { ns: 'test',
set: 'demo',
exp: exp,
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 an expression index on geospatial data.
Options for creating the index.
Optionalpolicy: 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 exp = Aerospike.exp.binGeo(binName)
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 an expression index.
Options for creating the index.
Optionalpolicy: null | policy.InfoPolicyThe Info Policy to use for this command.
A Promise that will resolve to an IndexJob instance.
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 exp = Aerospike.exp.binList(binName)
let indexName = 'recentLocationsIdx'
let indexType = Aerospike.indexType.LIST
let dataType = Aerospike.indexDataType.GEO2DSPHERE
let options = { ns: namespace,
set: set,
exp: exp,
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 an expression index on integer data.
Options for creating the index.
Optionalpolicy: 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 exp = Aerospike.exp.binInt(binName)
var indexName = 'ageIndex'
var options = { ns: 'test',
set: 'demo',
exp: exp,
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.
Creates an expression index on string data.
Options for creating the index.
Optionalpolicy: 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 exp = Aerospike.exp.binStr(binName)
var indexName = 'nameIndex'
var options = { ns: 'test',
set: 'demo',
exp: exp,
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.
Creates an index on geospatial data.
Options for creating the index.
Optionalpolicy: 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 index (Secondary index).
Options for creating the index.
Optionalpolicy: 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.
See indexDataType for supported index data types.
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 an index on integer data.
Options for creating the index.
Optionalpolicy: 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 with password and roles. Clear-text password will be hashed using bcrypt before sending to server.
User name for the new user.
Optionalroles: null | string[]Optional array of role names. For more information on roles, see admin.Role.
Optionalpolicy: null | policy.AdminPolicyOptional policy.AdminPolicy.
A promise that resolves to void upon success.
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'
})
await client.createPKIUser("khob", ["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()
}
})() User name for the new user.
Optionalroles: null | string[]Optional array of role names. For more information on roles, see admin.Role.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
User name for the new user.
Optionalroles: null | string[]Optional array of role names. For more information on roles, see admin.Role.
Optionalpolicy: null | policy.AdminPolicyOptional policy.AdminPolicy.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
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.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
Optionalwhitelist: null | string[]Optional list of allowable IP addresses assigned to role. IP addresses can contain wildcards (ie. 10.1.2.0/24).
OptionalreadQuota: null | numberOptional maximum reads per second limit, pass in zero for no limit.
OptionalwriteQuota: null | numberOptional maximum writes per second limit, pass in zero for no limit.
A promise that resolves to void upon success.
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'
})
await 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()
}
})() role name
List of privileges assigned to a role.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
Optionalwhitelist: null | string[]Optional list of allowable IP addresses assigned to role. IP addresses can contain wildcards (ie. 10.1.2.0/24).
OptionalreadQuota: null | numberOptional maximum reads per second limit, pass in zero for no limit.
OptionalwriteQuota: null | numberOptional maximum writes per second limit, pass in zero for no limit.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
Creates an index on string data.
Options for creating the index.
Optionalpolicy: 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 roles. PKI users are authenticated via TLS and a certificate instead of a password.
User name for the new user.
User password in clear-text format.
Optionalroles: null | string[]Optional array of role names. For more information on roles, see admin.Role.
Optionalpolicy: null | policy.AdminPolicyOptional policy.AdminPolicy.
A promise that resolves to void upon success.
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'
})
await 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()
}
})() User name for the new user.
User password in clear-text format.
Optionalroles: null | string[]Optional array of role names. For more information on roles, see admin.Role.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
User name for the new user.
User password in clear-text format.
Optionalroles: null | string[]Optional array of role names. For more information on roles, see admin.Role.
Optionalpolicy: null | policy.AdminPolicyOptional policy.AdminPolicy.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
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
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise that resolves to void upon success.
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.
await 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()
}
})() role name
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
role name
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
Remove a User from cluster
User name to be dropped.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise that resolves to void upon success.
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.
await 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()
}
})() User name to be dropped.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
User name to be dropped.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
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,
appId: "ecentral"
labels: {"size": "large", "fit": "regular"}
}
)
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 Symbols.
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.
Optionalpolicy: 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.
Optionalpolicy: 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.
Returns a serialized expression
serialized expression - base64 representation of the expression
Using the key provided, reads a record from the database cluster.
The key used to locate the record in the cluster.
Optionalpolicy: 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.
The key used to locate the record in the cluster.
The Read Policy to use for this command.
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 the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to EventEmitter.defaultMaxListeners.
Returns a list of all cluster nodes known to the client.
List of node objects
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()
}) Grant privileges to an user defined role.
role name
list of privileges assigned to a role.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise that resolves to void upon success.
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.
await 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()
}
})() role name
list of privileges assigned to a role.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
role name
list of privileges assigned to a role.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
Grant user defined role.
User name for granted roles
Optional array of role names. For more information on roles, see admin.Role.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise that resolves to void upon success.
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.
await 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()
}
})() User name for granted roles
Optional array of role names. For more information on roles, see admin.Role.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
User name for granted roles
Optional array of role names. For more information on roles, see admin.Role.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
Alias for Client#add.
The key of the record.
The key-value mapping of bin names and the corresponding values to use to increment the bin values with.
Optionalmetadata: RecordMetadataMeta data.
Optionalpolicy: policy.OperatePolicyThe Operate Policy to use for this command.
A Promise that resolves to the results of the opertion.
Alias for Client#add.
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.
Alias for Client#add.
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 Client#add.
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 Operate Policy to use for this command.
The function to call when the command completes with the results of the command.
Removes the specified index.
The namespace on which the index was created.
The name of the index.
Optionalpolicy: null | policy.InfoPolicyThe Info Policy to use for this command.
A Promise that resolves once the command completes.
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()
})
}) The namespace on which the index was created.
The name of the index.
The function to call when the command completes with the result of the command.
The namespace on which the index was created.
The name of the index.
The Info Policy to use for this k.
The function to call when the command completes with the result of the command.
Sends an info query to a specific cluster node.
The info request to send.
See Host. The address of the cluster host to send the request to.
Optionalpolicy: null | policy.InfoPolicyThe Info Policy to use for this command.
A Promise that resolves to an info result string.
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.
since v3.11.0 - use Client#infoNode or Client#infoAny instead.
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()
})
}) The info request to send.
See Host. The address of the cluster host to send the request to.
The function to call when an info response from a cluster host is received.
The info request to send.
See Host. The address of the cluster host to send the request to.
The Info Policy to use for this command.
The function to call when an info response from a cluster host is received.
Sends an info query to all nodes in the cluster and collects the results.
Optionalrequest: stringThe info request to send.
Optionalpolicy: null | policy.InfoPolicyThe Info Policy to use for this command.
A Promise that resolves to an InfoAllResponse.
The request parameter is a string representing an info request. If it is not specified, a default set of info values will be returned.
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()
})
}) Optionalrequest: stringThe info request to send.
Optionalcallback: 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.
Optionalrequest: stringThe info request to send.
Optionalpolicy: null | policy.InfoPolicyThe Info Policy to use for this command.
Optionalcallback: 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.
Sends an info query to a single, randomly selected cluster node.
Optionalrequest: stringThe info request to send.
Optionalpolicy: null | policy.InfoPolicyThe Info Policy to use for this command.
A Promise that resolves to an info result string.
The request parameter is a string representing an info request. If it is not specified, a default set of info values will be returned.
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()
})
}) 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.
Optionalrequest: stringThe info request to send.
Optionalcallback: 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.
Optionalrequest: stringThe info request to send.
Optionalpolicy: null | policy.InfoPolicyThe Info Policy to use for this command.
Optionalcallback: 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.
Sends an info query to a single node in the cluster.
The info request to send.
The node to send the request to. See InfoNodeParam.
Optionalpolicy: null | policy.InfoPolicyThe Info Policy to use for this command.
A Promise that resolves to an info result string.
The request parameter is a string representing an info request. If it is not specified, a default set of info values will be returned.
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()
})
}) The info request to send.
The node to send the request to. See InfoNodeParam.
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.
The info request to send.
The node to send the request to. See InfoNodeParam.
The Info Policy to use for this command.
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.
Is client connected to any server nodes.
OptionalcheckTenderErrors: booleanWhether to consider a server node connection that has had 5 consecutive info request failures during cluster tender. Default is true.
true if the client is currently connected to any server nodes.
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.
The name of the event being listened for
Optionallistener: FunctionThe event handler 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] ] Alias for emitter.removeListener().
Rest...args: any[]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 The name of the event.
The callback function
Rest...args: any[]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 The name of the event.
The callback function
Rest...args: any[]Performs multiple operations on a single record.
The key of the record.
List of Operations to perform on the record.
Optionalmetadata: null | RecordMetadataMeta data.
Optionalpolicy: null | policy.OperatePolicyThe Operate Policy to use for this command.
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()
})
})
}) The key of the record.
List of Operations to perform on the record.
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.
The key of the record.
List of Operations to perform on the record.
Meta data.
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.
The key of the record.
List of Operations to perform on the record.
Meta data.
The Operate Policy to use for this command.
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.
Shortcut for applying the operations.prepend operation to one or more record bins.
The key of the record.
The key-value mapping of bin names and the corresponding values to prepend to the bin value.
Optionalmetadata: null | RecordMetadataMeta data.
Optionalpolicy: 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 prepend to the bin value.
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 prepend to the bin value.
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 prepend to the bin value.
Meta data.
The Operate Policy to use for this command.
The function to call when the command completes with the results of the command.
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.
The name of the event.
The callback function
Rest...args: any[]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.
The name of the event.
The callback function
Rest...args: any[]Writes a record to the database cluster.
The key of the record.
A record object used for specifying the fields to store.
Optionalmeta: null | RecordMetadataMeta data.
Optionalpolicy: null | policy.WritePolicyThe Write Policy to use for this command.
A Promise that resolves to a Record.
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.
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()
})
})
}) The key of the record.
A record object used for specifying the fields to store.
The function to call when the command completes with the result of the command.
The key of the record.
A record object used for specifying the fields to store.
Meta data.
The function to call when the command completes with the result of the command.
The key of the record.
A record object used for specifying the fields to store.
Meta data.
The Write Policy to use for this command.
The function to call when the command completes with the result of the command.
Creates a new Query instance, which is used to define query in the database.
The namespace to be queried.
Optionaloptions: QueryOptionsQuery parameters. See Query constructor for details.
A Promise that resolves to a Query.
The namespace to be queried.
The set on which the query is to be executed.
Optionaloptions: QueryOptionsQuery parameters. See Query constructor for details.
Retrieves an admin.Role from the database.
role name filter.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise which resolves to an instance of admin.Role upon success. For more information on roles, see admin.Role.
const Aerospike = require('aerospike')
;(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()
}
})() Retrieves an admin.Role from the database.
role name filter.
Optionalcallback: TypedCallback<Role>The function to call when the command has completed.
Retrieves an admin.Role from the database.
role name filter.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
Optionalcallback: TypedCallback<Role>The function to call when the command has completed.
Retrieve all roles and role information from the database.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise which resolve to a list of admin.Role instances upon sucess. For more information on roles, see admin.Role.
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()
}
})() Optionalcallback: TypedCallback<Role[]>The function to call when the command has completed.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
Optionalcallback: TypedCallback<Role[]>The function to call when the command has completed.
Retrieves an admin.User from the database.
User name filter.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise which resolves to an instance of admin.User upon sucess. For more information on roles, see admin.User.
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()
}
})() User name filter.
Optionalcallback: TypedCallback<User>The function to call when the command has completed.
User name filter.
Optional AdminPolicy.
Optionalcallback: TypedCallback<User>The function to call when the command has completed.
Retrieves All user and user information from the database.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise which resolve to a list of admin.User instances upon success. For more information on roles, see admin.User.
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()
}
})() Optionalcallback: TypedCallback<User[]>The function to call when the command has completed.
Optional AdminPolicy.
Optionalcallback: TypedCallback<User[]>The function to call when the command has completed.
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'); Removes a record with the specified key from the database cluster.
The key of the record.
Optionalpolicy: null | policy.RemovePolicyThe Remove Policy to use for this command.
A Promise that resolves to the Key of the removed record.
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()
})
})
}) The key of the record.
The function to call when the command completes with the results of the command.
The key of the record.
The Remove Policy to use for this command.
The function to call when the command completes with the results of the command.
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.
OptionaleventName: string | symbolRemoves 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.
Rest...args: any[]Removes a seed host from the cluster.
Hostname/IP address of the seed host
Optionalport: numberPort number; defaults to Config#port or 3000.
Revoke privileges from an user defined role.
role name
List of privileges assigned to a role.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise that resolves to void upon success.
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.
await 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()
}
})() role name
List of privileges assigned to a role.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
role name
List of privileges assigned to a role.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
Remove roles from user's list of roles.
User name for revoked roles.
Optional array of role names. For more information on roles, see admin.Role.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise that resolves to void upon success.
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.
await 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()
}
})() User name for revoked roles.
Optional array of role names. For more information on roles, see admin.Role.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
User name for revoked roles.
Optional array of role names. For more information on roles, see admin.Role.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
Creates a new Scan instance in order to execute a database scan using the Scan API.
The namescape.
Optionaloptions: ScanOptionsScan parameters. See Scan constructor for details.
A Promise that resolves to a Query.
Scan constructor for options that can be used to initialize a new instance.
The namescape.
Optionalset: stringThe name of a set.
Optionaloptions: ScanOptionsScan parameters. See Scan constructor for details.
A Promise that resolves to a Query.
Retrieves selected bins for a record of given key from the database cluster.
The key of the record.
A list of bin names for the bins to be returned.
Optionalpolicy: null | policy.ReadPolicyThe Read Policy to use for this command.
A Promise that resolves to a AerospikeRecord.
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()
})
})
}) The key of the record.
A list of bin names for the bins to be returned.
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.
The key of the record.
A list of bin names for the bins to be returned.
The Read Policy to use for this command.
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.
By default EventEmitters 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.
Client#setPassword
Set user's password by user administrator. Clear-text password will be hashed using bcrypt before sending to server.
User name for the password change.
User password in clear-text format.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise that resolves to void upon success.
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.
await client.setPassword("khob", "TryTiger7!", ["Engineer"])
} catch (error) {
console.error('Error:', error)
process.exit(1)
} finally {
if (client) client.close()
}
})() User name for the password change.
User password in clear-text format.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
User name for the password change.
User password in clear-text format.
Optional AdminPolicy.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
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.
role name
maximum reads per second limit, pass in zero for no limit.
maximum writes per second limit, pass in zero for no limit.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise that resolves to void upon success.
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.
await 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()
}
})() 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.
role name
maximum reads per second limit, pass in zero for no limit.
maximum writes per second limit, pass in zero for no limit.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
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.
role name
maximum reads per second limit, pass in zero for no limit.
maximum writes per second limit, pass in zero for no limit.
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
Set IP address whitelist for a role. If whitelist is null or empty, remove existing whitelist from role.
role name
Optional list of allowable IP addresses assigned to role. IP addresses can contain wildcards (ie. 10.1.2.0/24).
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
A promise that resolves to void upon success.
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.
await 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()
}
})() Set IP address whitelist for a role. If whitelist is null or empty, remove existing whitelist from role.
role name
Optional list of allowable IP addresses assigned to role. IP addresses can contain wildcards (ie. 10.1.2.0/24).
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
Set IP address whitelist for a role. If whitelist is null or empty, remove existing whitelist from role.
role name
Optional list of allowable IP addresses assigned to role. IP addresses can contain wildcards (ie. 10.1.2.0/24).
Optionalpolicy: null | policy.AdminPolicyOptional AdminPolicy.
Optionalcallback: TypedCallback<void>The function to call when the command has completed.
Set XDR filter for given datacenter name and namespace. The expression filter indicates which records XDR should ship to the datacenter.
aerospike expression
Datacenter name.
Namespace.
Optionalpolicy: InfoPolicyThe Info Policy to use for this command.
A Promise that resolves to void.
Set XDR filter for given datacenter name and namespace. The expression filter indicates which records XDR should ship to the datacenter.
aerospike expression
Datacenter name.
Namespace.
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.
Set XDR filter for given datacenter name and namespace. The expression filter indicates which records XDR should ship to the datacenter.
aerospike expression
Datacenter name.
Namespace.
The Info Policy to use for this command.
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 runtime stats about the client instance.
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()
}) Removes records in specified namespace/set efficiently.
Required namespace.
Optional set name. Set to null to delete all sets in namespace.
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.
Optionalpolicy: null | policy.InfoPolicyThe Info Policy to use for this command.
A Promise that resolves when the truncate is complete.
Required namespace.
Required namespace.
Optional set name. Set to null to delete all sets in namespace.
Required namespace.
Optional set name. Set to null to delete all sets in namespace.
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.
Required namespace.
Optional set name. Set to null to delete all sets in namespace.
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.
The Info Policy to use for this command.
Registers a UDF module with the database cluster.
The file path to the Lua script to load into the server.
OptionaludfType: null | LUALanguage of the UDF script. Lua is the default and only supported scripting language for UDF modules at the moment; ref. language.
Optionalpolicy: null | policy.InfoPolicyThe Info Policy to use for this command.
A Promise that resolves to a Job instance.
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.
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()
})
})
}) The file path to the Lua script to load into the server.
Optionalpolicy: null | policy.InfoPolicyThe Info Policy to use for this command.
A Promise that resolves to a Job instance.
The file path to the Lua script to load into the server.
The function to call when the command completes with the result of the command.
The file path to the Lua script to load into the server.
Language of the UDF script. Lua is the default and only supported scripting language for UDF modules at the moment; ref. language.
The function to call when the command completes with the result of the command.
The file path to the Lua script to load into the server.
The Info Policy to use for this command.
The function to call when the command completes with the result of the command.
The file path to the Lua script to load into the server.
Language of the UDF script. Lua is the default and only supported scripting language for UDF modules at the moment; ref. language.
The Info Policy to use for this command.
The function to call when the command completes with the result of the command.
Removes a UDF module from the cluster.
The basename of the UDF module, without the local pathname but including the file extension (".lua").
Optionalpolicy: null | policy.InfoPolicyThe Info Policy to use for this command.
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.
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()
})
})
}) The basename of the UDF module, without the local pathname but including the file extension (".lua").
The function to call when the command completes with the result of the command.
The basename of the UDF module, without the local pathname but including the file extension (".lua").
The Info Policy to use for this command.
The function to call when the command completes with the result of the command.
Updates log settings for the client.
StaticaddListens 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 AbortSignals 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]();
}
} Disposable that removes the abort listener.
StaticgetReturns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on the emitter.
For EventTargets 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] ]
} StaticgetReturns the currently set max amount of listeners.
For EventEmitters this behaves exactly the same as calling .getMaxListeners on the emitter.
For EventTargets 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
} StaticlistenerA 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 The emitter to query
The event name
Staticonimport { 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' Optionaloptions: StaticEventEmitterIteratorOptionsAn AsyncIterator that iterates eventName events emitted by the emitter
Optionaloptions: StaticEventEmitterIteratorOptionsStaticonceCreates 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! Optionaloptions: StaticEventEmitterOptionsOptionaloptions: StaticEventEmitterOptionsStaticsetimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter); Optionaln: 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.
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.