Class Client

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.

Hierarchy

  • EventEmitter
    • Client

Constructors

Properties

captureStackTraces: boolean

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).

<code>true</code>, if
<code>process.env.AEROSPIKE_DEBUG_STACKTRACES</code> is set;
<code>false</code> otherwise.
config: Config

A copy of the configuration with which the client was initialized.

captureRejections: boolean

Value: boolean

Change the default captureRejections option on all new EventEmitter objects.

v13.4.0, v12.16.0

captureRejectionSymbol: typeof captureRejectionSymbol

Value: Symbol.for('nodejs.rejection')

See how to write a custom rejection handler.

v13.4.0, v12.16.0

defaultMaxListeners: number

By 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'.

v0.11.2

errorMonitor: typeof errorMonitor

This 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.

v13.6.0, v12.17.0

Methods

  • Type Parameters

    • K

    Parameters

    • error: Error
    • event: string | symbol
    • Rest...args: AnyRest

    Returns void

  • Parameters

    • transaction: Transaction

      Transaction instance.

    • callback: Function

      This function will be called with the result returned by the abort function call.

    Returns void

    v6.0.0

    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()
    })();
  • Parameters

    Returns Promise<
        | 0
        | 1
        | 2
        | 3>

    A Promise that resolves to the value returned by abort.

  • Alias for emitter.on(eventName, listener).

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v0.1.26

  • Adds a seed host to the cluster.

    Parameters

    • hostname: string

      Hostname/IP address of the new seed host

    • Optionalport: number

      Port number; defaults to Config#port or 3000.

    Returns void

    v2.6.0

  • Shortcut for applying the operations.append operation to one or more record bins.

    Parameters

    • key: KeyOptions

      The key of the record.

    • bins: AerospikeBins

      The key-value mapping of bin names and the corresponding values to 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 | RecordMetadata

      Meta data.

    • Optionalpolicy: null | policy.OperatePolicy

      The Operate Policy to use for this command.

    Returns Promise<AerospikeRecord>

    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.

  • Parameters

    • key: KeyOptions

      The key of the record.

    • bins: AerospikeBins

      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.

    • callback: TypedCallback<AerospikeRecord>

      The function to call when the command completes with the results of the command.

    Returns void

  • Parameters

    • key: KeyOptions

      The key of the record.

    • bins: AerospikeBins

      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.

    • metadata: null | RecordMetadata

      Meta data.

    • callback: TypedCallback<AerospikeRecord>

      The function to call when the command completes with the results of the command.

    Returns void

  • Parameters

    • key: KeyOptions

      The key of the record.

    • bins: AerospikeBins

      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.

    • metadata: null | RecordMetadata

      Meta data.

    • policy: null | policy.OperatePolicy

      The Operate Policy to use for this command.

    • callback: TypedCallback<AerospikeRecord>

      The function to call when the command completes with the results of the command.

    Returns void

  • Applies a User Defined Function (UDF) on a record in the database.

    Parameters

    • key: KeyOptions

      The key, used to locate the record in the cluster.

    • udfArgs: UDF

      Parameters used to specify which UDF function to execute.

    • Optionalpolicy: null | policy.ApplyPolicy

      The Apply Policy to use for this command.

    Returns Promise<AerospikeRecord>

    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.

    v2.0

    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)
    })
    })
  • Parameters

    • key: KeyOptions

      The key, used to locate the record in the cluster.

    • udfArgs: UDF

      Parameters used to specify which UDF function to execute.

    • callback: TypedCallback<AerospikeRecord>

      This function will be called with the result returned by the Record UDF function call.

    Returns void

  • Parameters

    • key: KeyOptions

      The key, used to locate the record in the cluster.

    • udfArgs: UDF

      Parameters used to specify which UDF function to execute.

    • policy: null | policy.ApplyPolicy

      The Apply Policy to use for this command.

    • callback: TypedCallback<AerospikeRecord>

      This function will be called with the result returned by the Record UDF function call.

    Returns void

  • Apply UDF (user defined function) on multiple keys.

    Parameters

    • keys: KeyOptions[]

      An array of keys, used to locate the records in the cluster.

    • udf: UDF

      Server UDF module/function and argList to apply.

    • OptionalbatchPolicy: null | policy.BatchPolicy

      The Batch Policy to use for this command.

    • OptionalbatchApplyPolicy: null | policy.BatchApplyPolicy

      UDF policy configuration parameters.

    Returns Promise<BatchResult[]>

    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.

    v5.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();
    })(); *
    function updateRecord(rec, binName, binValue)
    rec[binName] = binValue
    aerospike:update(rec)
    return binValue
    end
  • Parameters

    • keys: KeyOptions[]

      An array of keys, used to locate the records in the cluster.

    • udf: UDF

      Server UDF module/function and argList to apply.

    • Optionalcallback: TypedCallback<BatchResult[]>

      The function to call when the command completes. Includes the results of the batched command.

    Returns void

  • Parameters

    • keys: KeyOptions[]

      An array of keys, used to locate the records in the cluster.

    • udf: UDF

      Server UDF module/function and argList to apply.

    • OptionalbatchPolicy: policy.BatchPolicy

      The Batch Policy to use for this command.

    • Optionalcallback: TypedCallback<BatchResult[]>

      The function to call when the command completes, with the results of the batched command.

    Returns void

  • Parameters

    • keys: KeyOptions[]

      An array of keys, used to locate the records in the cluster.

    • udf: UDF

      Server UDF module/function and argList to apply.

    • OptionalbatchPolicy: policy.BatchPolicy

      The Batch Policy to use for this command.

    • OptionalbatchApplyPolicy: policy.BatchApplyPolicy

      UDF policy configuration parameters.

    • Optionalcallback: TypedCallback<BatchResult[]>

      The function to call when the command completes, with the results of the batched command.

    Returns void

  • Checks the existence of a batch of records from the database cluster.

    Parameters

    • keys: KeyOptions[]

      An array of Keys used to locate the records in the cluster.

    • Optionalpolicy: null | policy.BatchPolicy

      The Batch Policy to use for this command.

    Returns Promise<BatchResult[]>

    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();
    })();
  • Parameters

    • keys: KeyOptions[]

      An array of Keys used to locate the records in the cluster.

    • callback: TypedCallback<BatchResult[]>

      The function to call when the command completes, with the results of the batched command.

    Returns void

  • Parameters

    • keys: KeyOptions[]

      An array of Keys used to locate the records in the cluster.

    • policy: null | policy.BatchPolicy

      The Batch Policy to use for this command.

    • callback: TypedCallback<BatchResult[]>

      The function to call when the command completes, with the results of the batched command.

    Returns void

  • Reads a batch of records from the database cluster.

    Parameters

    • keys: KeyOptions[]

      An array of Keys, used to locate the records in the cluster.

    • Optionalpolicy: null | policy.BatchPolicy

      The Batch Policy to use for this command.

    Returns Promise<BatchResult[]>

    • 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.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();
    })();
  • Parameters

    • keys: KeyOptions[]

      An array of Keys, used to locate the records in the cluster.

    • callback: TypedCallback<BatchResult[]>

      The function to call when the command completes, with the results of the batched command.

    Returns void

  • Parameters

    • keys: KeyOptions[]

      An array of Keys, used to locate the records in the cluster.

    • policy: null | policy.BatchPolicy

      The Batch Policy to use for this command.

    • callback: TypedCallback<BatchResult[]>

      The function to call when the command completes, with the results of the batched command.

    Returns void

  • Read multiple records for specified batch keys in one batch call.

    Parameters

    Returns Promise<BatchResult[]>

    • A Promise that resolves to the results of the batched command.

    This method allows different namespaces/bins to be requested for each key in the batch. This method requires server >= 3.6.0.

    v2.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();
    })();
  • Parameters

    Returns void

  • Parameters

    Returns void

  • Remove multiple records.

    Parameters

    • keys: KeyOptions[]

      Key An array of keys, used to locate the records in the cluster.

    • OptionalbatchPolicy: null | policy.BatchPolicy

      The Batch Policy to use for this command.

    • OptionalbatchRemovePolicy: null | policy.BatchRemovePolicy

      Remove policy configuration parameters.

    Returns Promise<BatchResult[]>

    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.

    v5.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();
    })();
  • Parameters

    • keys: KeyOptions[]

      Key An array of keys, used to locate the records in the cluster.

    • Optionalcallback: TypedCallback<BatchResult[]>

      The function to call when the command completes, with the results of the batched command.

    Returns void

  • Parameters

    • keys: KeyOptions[]

      Key An array of keys, used to locate the records in the cluster.

    • OptionalbatchPolicy: null | policy.BatchPolicy

      The Batch Policy to use for this command.

    • Optionalcallback: TypedCallback<BatchResult[]>

      The function to call when the command completes, with the results of the batched command.

    Returns void

  • Parameters

    • keys: KeyOptions[]

      Key An array of keys, used to locate the records in the cluster.

    • OptionalbatchPolicy: null | policy.BatchPolicy

      The Batch Policy to use for this command.

    • OptionalbatchRemovePolicy: null | policy.BatchRemovePolicy

      Remove policy configuration parameters.

    • Optionalcallback: TypedCallback<BatchResult[]>

      The function to call when the command completes, with the results of the batched command.

    Returns void

  • Reads a subset of bins for a batch of records from the database cluster.

    Parameters

    • keys: KeyOptions[]

      An array of keys, used to locate the records in the cluster.

    • bins: string[]

      An array of bin names for the bins to be returned for the given keys.

    • Optionalpolicy: policy.BatchPolicy

      The Batch Policy to use for this command.

    Returns Promise<BatchSelectRecord[]>

    • If no callback function is passed, the function returns a Promise that resolves to the results of the batched 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();
    })();
  • Parameters

    • keys: KeyOptions[]

      An array of keys, used to locate the records in the cluster.

    • bins: string[]

      An array of bin names for the bins to be returned for the given keys.

    • callback: TypedCallback<BatchSelectRecord[]>

      The function to call when the command completes, with the results of the batched command.

    Returns void

  • Parameters

    • keys: KeyOptions[]

      An array of keys, used to locate the records in the cluster.

    • bins: string[]

      An array of bin names for the bins to be returned for the given keys.

    • policy: policy.BatchPolicy

      The Batch Policy to use for this command.

    • callback: TypedCallback<BatchSelectRecord[]>

      The function to call when the command completes, with the results of the batched command.

    Returns void

  • 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.

    Parameters

    Returns Promise<BatchResult[]>

    v6.0.0

    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();
    })();
  • Parameters

    Returns void

  • Parameters

    Returns void

  • Client#changePassword

    Change a user's password.

    Parameters

    • user: string

      User name for the password change.

    • password: string

      User password in clear-text format.

    • Optionalpolicy: null | policy.AdminPolicy

      Optional AdminPolicy.

    Returns void

    const Aerospike = require('aerospike')

    function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
    }

    ;(async function () {
    let client
    try {
    client = await Aerospike.connect({
    hosts: '192.168.33.10:3000',
    policies: {
    write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
    },
    // Must have security enabled in server configuration before user and password configurations can be used.
    user: 'admin',
    password: 'admin'
    })

    // User must be created before password is changed. See {@link Client#createUser} for an example.
    client.changePassword("khob", "TryTiger7!", ["Engineer"])
    } catch (error) {
    console.error('Error:', error)
    process.exit(1)
    } finally {
    if (client) client.close()
    }
    })()
  • Closes the client connection to the cluster.

    Parameters

    • OptionalreleaseEventLoop: boolean

      Whether to release the event loop handle after the client is closed. Default is false

    Returns void

    releaseEventLoop

    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)
    })
  • Parameters

    • transaction: Transaction

      Transaction instance.

    • callback: Function

      This function will be called with the result returned by the commit function call.

    Returns void

    v6.0.0

    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()
    })();
  • Parameters

    Returns Promise<
        | 0
        | 1
        | 2
        | 3
        | 4
        | 5>

    A Promise that resolves to the Transaction.commitStatus returned by commit.

    })();

  • Establishes the connection to the cluster.

    Parameters

    • Optionalcallback: TypedCallback<Client>

      The function to call once the client connection has been established successfully and the client is ready to accept commands.

    Returns Promise<Client>

    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.

    if event loop resources have already been released.

    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

    Parameters

    • serializedContext: string

      base64 serialized {link cdt.Context}

    Returns Context

    Deserialized CDT Context

    contextFromBase64 for a usage example.

    v5.6.0

  • Returns a serialized CDT Context

    Parameters

    Returns string

    serialized context - base64 representation of the CDT Context

    v5.6.0

    const Aerospike = require('aerospike');
    const Context = Aerospike.cdt.Context
    // Define host configuration
    let config = {
    hosts: '192.168.33.10:3000',
    policies: {
    operate : new Aerospike.OperatePolicy({socketTimeout : 0, totalTimeout : 0}),
    write : new Aerospike.WritePolicy({socketTimeout : 0, totalTimeout : 0}),
    read : new Aerospike.ReadPolicy({socketTimeout : 0, totalTimeout : 0})
    }
    }


    Aerospike.connect(config, async (error, client) => {
    // Create a context
    let context = new Context().addMapKey('nested')

    // Create keys for records to be written
    let recordKey = new Aerospike.Key('test', 'demo', 'record')
    let contextKey = new Aerospike.Key('test', 'demo', 'context')

    // Put record with a CDT
    await client.put(recordKey, {exampleBin: {nested: {food: 'blueberry', drink: 'koolaid'}}})

    // Test the context with client.operate()
    var ops = [
    Aerospike.maps.getByKey('exampleBin', 'food', Aerospike.maps.returnType.KEY_VALUE).withContext(context)
    ]
    let results = await client.operate(recordKey, ops)
    console.log(results.bins.exampleBin) // [ 'food', 'blueberry' ]

    // Serialize CDT Context
    let serializedContext = client.contextToBase64(context)

    // Put record with bin containing the serialized record
    await client.put(contextKey, {context: serializedContext})

    // Get context when needed for command
    let contextRecord = await client.get(contextKey)

    // Deserialize CDT Context
    context = client.contextFromBase64(contextRecord.bins.context)

    // Test the context with client.operate()
    ops = [
    Aerospike.maps.getByKey('exampleBin', 'food', Aerospike.maps.returnType.KEY_VALUE).withContext(context)
    ]
    results = await client.operate(recordKey, ops)
    console.log(results.bins.exampleBin) // [ 'food', 'blueberry' ]

    // Close the client
    client.close()
    })
  • Creates a blob secondary index index.

    This is a short-hand for calling Client#createIndex with the datatype option set to Aerospike.indexDataType.BLOB.

    Parameters

    Returns Promise<IndexJob>

    • A Promise that will resolve to an IndexJob 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

    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()
    })
    })
  • Parameters

    Returns void

  • Parameters

    Returns void

  • Creates a geospatial secondary secondary index.

    Parameters

    Returns Promise<IndexJob>

    • A Promise that will resolve to an IndexJob instance.

    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()
    })
    })
  • Parameters

    Returns void

  • Parameters

    Returns void

  • Creates a secondary index (SI).

    Parameters

    Returns Promise<IndexJob>

    A Promise that will resolve to an IndexJob instance.

    Calling the createIndex method issues an index create command to the Aerospike cluster and returns immediately. To verify that the index has been created and populated with all the data use the IndexJob instance returned by the callback.

    Aerospike currently supports indexing of strings, integers and geospatial information in GeoJSON format.

    A string index allows for equality lookups. An equality lookup means that if you query for an indexed bin with value "abc", then only records containing bins with "abc" will be returned.

    An integer index allows for either equality or range lookups. An equality lookup means that if you query for an indexed bin with value 123, then only records containing bins with the value 123 will be returned. A range lookup means that if you can query bins within a range. So, if your range is (1...100), then all records containing a value in that range will be returned.

    A geo 2d sphere index allows either "contains" or "within" lookups. A "contains" lookup means that if you query for an indexed bin with GeoJSON point element, then only records containing bins with a GeoJSON element containing that point will be returned. A "within" lookup means that if you query for an indexed bin with a GeoJSON polygon element, then all records containing bins with a GeoJSON element wholly contained within that polygon will be returned.

    v2.0

    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()
    })
    })
    })
  • Parameters

    Returns void

  • Parameters

    Returns void

  • Creates a SI of type Integer.

    Parameters

    Returns Promise<IndexJob>

    • A Promise that will resolve to an IndexJob instance.

    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()
    })
    })
  • Parameters

    Returns void

    • A Promise that will resolve to an IndexJob instance.
  • Parameters

    Returns void

    • A Promise that will resolve to an IndexJob instance.
  • Create user defined role with optional privileges, whitelist and read/write quotas. Quotas require server security configuration "enable-quotas" to be set to true.

    Parameters

    • roleName: string

      role name

    • privileges: Privilege[]

      List of privileges assigned to a role.

    • Optionalpolicy: null | policy.AdminPolicy

      Optional 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 | number

      Optional maximum reads per second limit, pass in zero for no limit.

    • OptionalwriteQuota: null | number

      Optional maximum writes per second limit, pass in zero for no limit.

    Returns void

    const Aerospike = require('aerospike')

    function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
    }

    ;(async function () {
    let client
    try {
    client = await Aerospike.connect({
    hosts: '192.168.33.10:3000',
    policies: {
    write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
    },
    // Must have security enabled in server configuration before user and password configs can be used.
    user: 'admin',
    password: 'admin'
    })

    client.createRole("Engineer", [new Aerospike.admin.Privilege(Aerospike.privilegeCode.READ_WRITE), new Aerospike.admin.Privilege(Aerospike.privilegeCode.TRUNCATE)], null)
    // Must wait a short length of time of the role to be fully created.
    await wait(5)
    const role = await client.queryRole("Engineer", null)
    console.log(role)
    } catch (error) {
    console.error('Error:', error)
    process.exit(1)
    } finally {
    if (client) client.close()
    }
    })()
  • Creates a SI of type String.

    Parameters

    Returns Promise<IndexJob>

    • A Promise that will resolve to an IndexJob instance.

    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()
    })
    })
  • Parameters

    Returns void

  • Parameters

    Returns void

  • Create user with password and roles. Clear-text password will be hashed using bcrypt before sending to server.

    Parameters

    • user: string

      User name for the new user.

    • password: string

      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.AdminPolicy

    Returns void

    const Aerospike = require('aerospike')

    function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
    }

    ;(async function () {
    let client
    try {
    client = await Aerospike.connect({
    hosts: '192.168.33.10:3000',
    policies: {
    write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
    },
    // Must have security enabled in server configuration before user and password configurations can be used.
    user: 'admin',
    password: 'admin'
    })

    client.createUser("khob", "MightyMice55!", ["Engineer"])
    // Must wait a short length of time of the user to be fully created.
    await wait(5)
    const user = await client.queryUser("khob", null)
    console.log(user)
    } catch (error) {
    console.error('Error:', error)
    process.exit(1)
    } finally {
    if (client) client.close()
    }
    })()
  • Disable extended periodic cluster and node latency metrics.

    Returns Promise<void>

    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.

    Parameters

    • callback: Function

      This function will be called with the result returned by the disableMetrics call.

    Returns void

  • Drop user defined role.

    Parameters

    Returns void

    const Aerospike = require('aerospike')

    function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
    }

    ;(async function () {
    let client
    try {
    client = await Aerospike.connect({
    hosts: '192.168.33.10:3000',
    policies: {
    write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
    },
    // Must have security enabled in server configuration before user and password configurations can be used.
    user: 'admin',
    password: 'admin'
    })

    // A role must be created before a role can be dropped. See {@link Client#createRole} for an example.
    client.dropRole("Engineer")
    // Must wait a short length of time of the role to be fully dropped.
    await wait(5)
    let roles = await client.queryRoles()
    // 'Engineer' should no longer appear in the logged list of roles
    console.log(roles)
    } catch (error) {
    console.error('Error:', error)
    process.exit(1)
    } finally {
    if (client) client.close()
    }
    })()
  • Remove a User from cluster

    Parameters

    Returns void

    const Aerospike = require('aerospike')

    function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
    }

    ;(async function () {
    let client
    try {
    client = await Aerospike.connect({
    hosts: '192.168.33.10:3000',
    policies: {
    write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
    },
    // Must have security enabled in server configuration before user and password configurations can be used.
    user: 'admin',
    password: 'admin'
    })

    // A user must be created before a user can be dropped. See {@link Client#createUser} for an example.
    client.dropUser("khob")
    // Must wait a short length of time of the role to be fully dropped.
    await wait(5)
    let users = await client.queryUsers()
    // 'khob' should no longer appear in the logged list of roles
    console.log(users)
    } catch (error) {
    console.error('Error:', error)
    process.exit(1)
    } finally {
    if (client) client.close()
    }
    })()
  • Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.

    Returns true if the event had listeners, false otherwise.

    import { EventEmitter } from 'node:events';
    const myEmitter = new EventEmitter();

    // First listener
    myEmitter.on('event', function firstListener() {
    console.log('Helloooo! first listener');
    });
    // Second listener
    myEmitter.on('event', function secondListener(arg1, arg2) {
    console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
    });
    // Third listener
    myEmitter.on('event', function thirdListener(...args) {
    const parameters = args.join(', ');
    console.log(`event with parameters ${parameters} in third listener`);
    });

    console.log(myEmitter.listeners('event'));

    myEmitter.emit('event', 1, 2, 3, 4, 5);

    // Prints:
    // [
    // [Function: firstListener],
    // [Function: secondListener],
    // [Function: thirdListener]
    // ]
    // Helloooo! first listener
    // event with parameters 1, 2 in second listener
    // event with parameters 1, 2, 3, 4, 5 in third listener

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • Rest...args: AnyRest

    Returns boolean

    v0.1.26

  • Enable extended periodic cluster and node latency metrics.

    Returns Promise<void>

    A Promise that resolves to void.

    const Aerospike = require('aerospike')

    // INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
    var config = {
    hosts: '192.168.33.10:3000',
    }


    ;(async () => {
    let client = await Aerospike.connect(config)

    client.enableMetrics()

    client.disableMetrics()


    await client.close()
    })();
    const Aerospike = require('aerospike')

    // INSERT HOSTNAME AND PORT NUMBER OF AEROSPIKE SERVER NODE HERE!
    var config = {
    hosts: '192.168.33.10:3000',
    }


    function enableListener() {
    console.log("Metrics Enabled")
    return
    }

    function snapshotListener(cluster: Cluster) {
    console.log(Cluster.clusterName)
    return
    }

    function nodeCloseListener(node: Node) {
    console.log(node.conns)
    return
    }

    function disableListener(cluster: Cluster) {
    console.log("Metrics Disabled")
    return
    }

    ;(async () => {
    let client = await Aerospike.connect(config)

    let listeners: MetricsListeners = new Aerospike.MetricsListeners({
    enableListener,
    disableListener,
    nodeCloseListener,
    snapshotListener
    }
    )


    let policy: MetricsPolicy = new MetricsPolicy({
    metricsListeners: listeners,
    reportDir: metricsLogFolder,
    reportSizeLimit: 1000,
    interval: 2,
    latencyColumns: 5,
    latencyShift: 2
    }
    )
    await client.enableMetrics(policy)


    await client.disableMetrics()

    // All listeners are fired asynchronously
    // If you need the enableListener or disableListener to fire immediately, yield control of the event loop.
    await new Promise(r => setTimeout(r, 0));

    await client.close()
  • Enable extended periodic cluster and node latency metrics.

    Parameters

    • callback: Function

      This function will be called with the result returned by the enableMetrics call.

    Returns void

  • Enable extended periodic cluster and node latency metrics.

    Parameters

    Returns Promise<void>

    A Promise that resolves to void.

  • Enable extended periodic cluster and node latency metrics.

    Parameters

    Returns void

  • 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) ]

    Returns (string | symbol)[]

    v6.0.0

  • Checks the existance of a record in the database cluster.

    Parameters

    • key: KeyOptions

      The key of the record to check for existance.

    • Optionalpolicy: null | policy.ReadPolicy

      The Read Policy to use for this command.

    Returns Promise<boolean>

    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)
    })
  • Parameters

    • key: KeyOptions

      The key of the record to check for existance.

    • callback: TypedCallback<boolean>

      The function to call when the command completes; the passed value is true if the record exists or false otherwise.

    Returns void

  • Parameters

    • key: KeyOptions

      The key of the record to check for existance.

    • policy: null | policy.ReadPolicy

      The Read Policy to use for this command.

    • callback: TypedCallback<boolean>

      The function to call when the command completes; the passed value is true if the record exists or false otherwise.

    Returns void

  • Checks the existance of a record in the database cluster.

    Parameters

    • key: KeyOptions

      The key of the record to check for existance.

    • Optionalpolicy: policy.ReadPolicy

      The Read Policy to use for this command.

    Returns Promise<AerospikeRecord>

    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)
    })
  • Parameters

    • key: KeyOptions

      The key of the record to check for existance.

    • callback: TypedCallback<AerospikeRecord>

      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 void

  • Parameters

    • key: KeyOptions

      The key of the record to check for existance.

    • policy: policy.ReadPolicy

      The Read Policy to use for this command.

    • callback: TypedCallback<AerospikeRecord>

      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 void

  • Using the key provided, reads a record from the database cluster.

    Parameters

    • key: KeyOptions

      The key used to locate the record in the cluster.

    • Optionalpolicy: policy.ReadPolicy

      The Read Policy to use for this command.

    Returns Promise<AerospikeRecord>

    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()
    })
    })
  • Parameters

    • key: KeyOptions

      The key used to locate the record in the cluster.

    • callback: TypedCallback<AerospikeRecord>

      The function to call when the command completes with the results of the command; if no callback function is provided, the method returns a Promise instead.

    Returns void

  • Parameters

    • key: KeyOptions

      The key used to locate the record in the cluster.

    • policy: policy.ReadPolicy

      The Read Policy to use for this command.

    • callback: TypedCallback<AerospikeRecord>

      The function to call when the command completes with the results of the command; if no callback function is provided, the method returns a Promise instead.

    Returns void

  • Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to EventEmitter.defaultMaxListeners.

    Returns number

    v1.0.0

  • Returns a list of all cluster nodes known to the client.

    Returns Node[]

    List of node objects

    v2.6.0

    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.

    Parameters

    Returns void

    const Aerospike = require('aerospike')

    function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
    }

    ;(async function () {
    let client
    try {
    client = await Aerospike.connect({
    hosts: '192.168.33.10:3000',
    policies: {
    write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
    },
    // Must have security enabled in server configuration before user and password configurations can be used.
    user: 'admin',
    password: 'admin'
    })

    // A role must be created before privileges can be granted. See {@link Client#createUser} for an example.
    client.grantPrivileges("Engineer", [new Aerospike.admin.Privilege(Aerospike.privilegeCode.SINDEX_ADMIN)])
    // Must wait a short length of time for the privilege to be granted.
    await wait(5)
    let role = await client.queryRole("Engineer")
    console.log(role)
    } catch (error) {
    console.error('Error:', error)
    process.exit(1)
    } finally {
    if (client) client.close()
    }
    })()
  • Drop user defined role.

    Parameters

    • user: string

      User name for granted roles

    • roles: string[]

      Optional array of role names. For more information on roles, see admin.Role.

    • Optionalpolicy: null | policy.AdminPolicy

      Optional AdminPolicy.

    Returns void

    const Aerospike = require('aerospike')

    function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
    }

    ;(async function () {
    let client
    try {
    client = await Aerospike.connect({
    hosts: '192.168.33.10:3000',
    policies: {
    write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
    },
    // Must have security enabled in server configuration before user and password configurations can be used.
    user: 'admin',
    password: 'admin'
    })

    // A user must be created before roles can be granted. See {@link Client#createUser} for an example.
    client.grantRoles("khob", ["Engineer"])
    // Must wait a short length of time for the role to be granted
    await wait(5)
    let user = await client.queryUser("khob")
    console.log(user)
    } catch (error) {
    console.error('Error:', error)
    process.exit(1)
    } finally {
    if (client) client.close()
    }
    })()
  • Removes the specified index.

    Parameters

    • namespace: string

      The namespace on which the index was created.

    • index: string

      The name of the index.

    • Optionalpolicy: null | policy.InfoPolicy

      The Info Policy to use for this command.

    Returns Promise<void>

    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()
    })
    })
  • Parameters

    • namespace: string

      The namespace on which the index was created.

    • index: string

      The name of the index.

    • callback: TypedCallback<void>

      The function to call when the command completes with the result of the command.

    Returns void

  • Parameters

    • namespace: string

      The namespace on which the index was created.

    • index: string

      The name of the index.

    • policy: null | policy.InfoPolicy

      The Info Policy to use for this k.

    • callback: TypedCallback<void>

      The function to call when the command completes with the result of the command.

    Returns void

  • Sends an info query to a specific cluster node.

    Parameters

    • request: string

      The info request to send.

    • host: string | Host

      See Host. The address of the cluster host to send the request to.

    • Optionalpolicy: null | policy.InfoPolicy

      The Info Policy to use for this command.

    Returns Promise<string>

    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()
    })
    })
  • Parameters

    • request: undefined | string

      The info request to send.

    • host: string | Host

      See Host. The address of the cluster host to send the request to.

    • callback: TypedCallback<string>

      The function to call when an info response from a cluster host is received.

    Returns void

  • Parameters

    • request: undefined | string

      The info request to send.

    • host: string | Host

      See Host. The address of the cluster host to send the request to.

    • policy: null | policy.InfoPolicy

      The Info Policy to use for this command.

    • callback: TypedCallback<string>

      The function to call when an info response from a cluster host is received.

    Returns void

  • Sends an info query to all nodes in the cluster and collects the results.

    Parameters

    • Optionalrequest: string

      The info request to send.

    • Optionalpolicy: null | policy.InfoPolicy

      The Info Policy to use for this command.

    Returns Promise<InfoAllResponse[]>

    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.

    v2.3.0

    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()
    })
    })
  • Parameters

    • Optionalrequest: string

      The 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.

    Returns void

  • Parameters

    • Optionalrequest: string

      The info request to send.

    • Optionalpolicy: null | policy.InfoPolicy

      The 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.

    Returns void

  • Sends an info query to a single, randomly selected cluster node.

    Parameters

    • Optionalrequest: string

      The info request to send.

    • Optionalpolicy: null | policy.InfoPolicy

      The Info Policy to use for this command.

    Returns Promise<string>

    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.

    v2.4.0

    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()
    })
    })
  • Parameters

    • callback: TypedCallback<string>

      The function to call once the node returns the response to the info command; if no callback function is provided, the method returns a Promise instead.

    Returns void

  • Parameters

    • Optionalrequest: string

      The 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.

    Returns void

  • Parameters

    • Optionalrequest: string

      The info request to send.

    • Optionalpolicy: null | policy.InfoPolicy

      The 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.

    Returns void

  • Sends an info query to a single node in the cluster.

    Parameters

    Returns Promise<string>

    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.

    v3.11.0

    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()
    })
    })
  • Parameters

    • request: undefined | string

      The info request to send.

    • node: InfoNodeParam

      The node to send the request to. See InfoNodeParam.

    • callback: TypedCallback<string>

      The function to call once the node returns the response to the info command; if no callback function is provided, the method returns a Promise instead.

    Returns void

  • Parameters

    • request: undefined | string

      The info request to send.

    • node: InfoNodeParam

      The node to send the request to. See InfoNodeParam.

    • policy: null | policy.InfoPolicy

      The Info Policy to use for this command.

    • callback: TypedCallback<string>

      The function to call once the node returns the response to the info command; if no callback function is provided, the method returns a Promise instead.

    Returns void

  • Is client connected to any server nodes.

    Parameters

    • OptionalcheckTenderErrors: boolean

      Whether to consider a server node connection that has had 5 consecutive info request failures during cluster tender. Default is true.

    Returns boolean

    true if the client is currently connected to any server nodes.

    v2.0

  • Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event being listened for

    • Optionallistener: Function

      The event handler function

    Returns number

    v3.2.0

  • Returns a copy of the array of listeners for the event named eventName.

    server.on('connection', (stream) => {
    console.log('someone connected!');
    });
    console.log(util.inspect(server.listeners('connection')));
    // Prints: [ [Function] ]

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

    Returns Function[]

    v0.1.26

  • Alias for emitter.removeListener().

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v10.0.0

  • Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

    server.on('connection', (stream) => {
    console.log('someone connected!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

    import { EventEmitter } from 'node:events';
    const myEE = new EventEmitter();
    myEE.on('foo', () => console.log('a'));
    myEE.prependListener('foo', () => console.log('b'));
    myEE.emit('foo');
    // Prints:
    // b
    // a

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v0.1.101

  • Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

    server.once('connection', (stream) => {
    console.log('Ah, we have our first user!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

    import { EventEmitter } from 'node:events';
    const myEE = new EventEmitter();
    myEE.once('foo', () => console.log('a'));
    myEE.prependOnceListener('foo', () => console.log('b'));
    myEE.emit('foo');
    // Prints:
    // b
    // a

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v0.3.0

  • Performs multiple operations on a single record.

    Parameters

    Returns Promise<AerospikeRecord>

    Operations can be created using the methods in one of the following modules:

    • operations - General operations on all types.
    • lists - Operations on CDT List values.
    • maps - Operations on CDT Map values.
    • bitwise - Operations on Bytes values.
    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()
    })
    })
    })
  • Parameters

    • key: KeyOptions

      The key of the record.

    • operations: Operation[]

      List of Operations to perform on the record.

    • callback: TypedCallback<AerospikeRecord>

      The function to call when the command completes with the results of the command; if no callback function is provided, the method returns a Promise instead.

    Returns void

  • Parameters

    Returns void

  • Parameters

    Returns void

  • Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

    server.prependListener('connection', (stream) => {
    console.log('someone connected!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v6.0.0

  • Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

    server.prependOnceListener('connection', (stream) => {
    console.log('Ah, we have our first user!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v6.0.0

  • Writes a record to the database cluster.

    Parameters

    Returns Promise<Key>

    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()
    })
    })
    })
  • Parameters

    Returns void

  • Parameters

    Returns void

  • Parameters

    Returns void

  • Creates a new Query instance, which is used to define query in the database.

    Parameters

    • ns: string

      The namespace to be queried.

    • Optionaloptions: QueryOptions

      Query parameters. See Query constructor for details.

    Returns Query

    A Promise that resolves to a Query.

    Query

    const filter = Aerospike.filter

    var statement = {}
    statment.filters: [filter.equal('color', 'blue')]

    var query = client.query(ns, set, statment)
    var stream = query.execute()
  • Parameters

    • ns: string

      The namespace to be queried.

    • set: null | string

      The set on which the query is to be executed.

    • Optionaloptions: QueryOptions

      Query parameters. See Query constructor for details.

    Returns Query

  • Retrieves an admin.Role from the database.

    Parameters

    Returns Role

    An instance of admin.Role. 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'
    })

    // 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()
    }
    })()
  • Retrieve all roles and role information from the database.

    Parameters

    Returns Role[]

    An list of admin.Role instances. 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()
    }
    })()
  • Retrieves an admin.User from the database.

    Parameters

    Returns User

    An instance of admin.User. 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()
    }
    })()
  • Retrieves All user and user information from the database.

    Parameters

    Returns User[]

    An list of admin.User instances. 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()
    }
    })()
  • Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

    import { EventEmitter } from 'node:events';
    const emitter = new EventEmitter();
    emitter.once('log', () => console.log('log once'));

    // Returns a new Array with a function `onceWrapper` which has a property
    // `listener` which contains the original listener bound above
    const listeners = emitter.rawListeners('log');
    const logFnWrapper = listeners[0];

    // Logs "log once" to the console and does not unbind the `once` event
    logFnWrapper.listener();

    // Logs "log once" to the console and removes the listener
    logFnWrapper();

    emitter.on('log', () => console.log('log persistently'));
    // Will return a new Array with a single function bound by `.on()` above
    const newListeners = emitter.rawListeners('log');

    // Logs "log persistently" twice
    newListeners[0]();
    emitter.emit('log');

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

    Returns Function[]

    v9.4.0

  • Removes a record with the specified key from the database cluster.

    Parameters

    Returns Promise<Key>

    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()
    })
    })
    })
  • Parameters

    • key: KeyOptions

      The key of the record.

    • callback: TypedCallback<Key>

      The function to call when the command completes with the results of the command.

    Returns void

  • Parameters

    • key: KeyOptions

      The key of the record.

    • policy: null | policy.RemovePolicy

      The Remove Policy to use for this command.

    • callback: TypedCallback<Key>

      The function to call when the command completes with the results of the command.

    Returns void

  • Removes all listeners, or those of the specified eventName.

    It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

    Returns a reference to the EventEmitter, so that calls can be chained.

    Parameters

    • OptionaleventName: string | symbol

    Returns this

    v0.1.26

  • Removes the specified listener from the listener array for the event named eventName.

    const callback = (stream) => {
    console.log('someone connected!');
    };
    server.on('connection', callback);
    // ...
    server.removeListener('connection', callback);

    removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

    Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.

    import { EventEmitter } from 'node:events';
    class MyEmitter extends EventEmitter {}
    const myEmitter = new MyEmitter();

    const callbackA = () => {
    console.log('A');
    myEmitter.removeListener('event', callbackB);
    };

    const callbackB = () => {
    console.log('B');
    };

    myEmitter.on('event', callbackA);

    myEmitter.on('event', callbackB);

    // callbackA removes listener callbackB but it will still be called.
    // Internal listener array at time of emit [callbackA, callbackB]
    myEmitter.emit('event');
    // Prints:
    // A
    // B

    // callbackB is now removed.
    // Internal listener array [callbackA]
    myEmitter.emit('event');
    // Prints:
    // A

    Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

    When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:

    import { EventEmitter } from 'node:events';
    const ee = new EventEmitter();

    function pong() {
    console.log('pong');
    }

    ee.on('ping', pong);
    ee.once('ping', pong);
    ee.removeListener('ping', pong);

    ee.emit('ping');
    ee.emit('ping');

    Returns a reference to the EventEmitter, so that calls can be chained.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v0.1.26

  • Removes a seed host from the cluster.

    Parameters

    • hostname: string

      Hostname/IP address of the seed host

    • Optionalport: number

      Port number; defaults to Config#port or 3000.

    Returns void

    v2.6.0

  • Revoke privileges from an user defined role.

    Parameters

    Returns void

    const Aerospike = require('aerospike')

    function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
    }

    ;(async function () {
    let client
    try {
    client = await Aerospike.connect({
    hosts: '192.168.33.10:3000',
    policies: {
    write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
    },
    // Must have security enabled in server configuration before user and password configurations can be used.
    user: 'admin',
    password: 'admin'
    })
    // A role must be created before privileges can be revoked. See {@link Client#createRole} for an example.
    client.revokePrivileges("Engineer", [new Aerospike.admin.Privilege(Aerospike.privilegeCode.SINDEX_ADMIN)])
    // Must wait a short length of time for the privilege to be granted.
    await wait(5)
    let users = await client.queryRole("Engineer")
    console.log(users)
    } catch (error) {
    console.error('Error:', error)
    process.exit(1)
    } finally {
    if (client) client.close()
    }
    })()
  • Remove roles from user's list of roles.

    Parameters

    • user: string

      User name for revoked roles.

    • roles: string[]

      Optional array of role names. For more information on roles, see admin.Role.

    • Optionalpolicy: null | policy.AdminPolicy

      Optional AdminPolicy.

    Returns void

    const Aerospike = require('aerospike')

    function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
    }

    ;(async function () {
    let client
    try {
    client = await Aerospike.connect({
    hosts: '192.168.33.10:3000',
    policies: {
    write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
    },
    // Must have security enabled in server configuration before user and password configurations can be used.
    user: 'admin',
    password: 'admin'
    })
    // A user must be created before roles can be revoked. See {@link Client#createUser} for an example.
    client.revokeRoles("khob", ["Engineer"])
    // Must wait a short length of time for the privilege to be granted.
    await wait(5)
    let user = await client.queryUser("khob")
    console.log(user)
    } catch (error) {
    console.error('Error:', error)
    process.exit(1)
    } finally {
    if (client) client.close()
    }
    })()
  • Creates a new Scan instance in order to execute a database scan using the Scan API.

    Parameters

    • ns: string

      The namescape.

    • Optionaloptions: ScanOptions

      Scan parameters. See Scan constructor for details.

    Returns Scan

    A Promise that resolves to a Query.

    Scan constructor for options that can be used to initialize a new instance.

    v2.0

  • Parameters

    • ns: string

      The namescape.

    • Optionalset: string

      The name of a set.

    • Optionaloptions: ScanOptions

      Scan parameters. See Scan constructor for details.

    Returns Scan

    A Promise that resolves to a Query.

  • Retrieves selected bins for a record of given key from the database cluster.

    Parameters

    • key: KeyOptions

      The key of the record.

    • bins: string[]

      A list of bin names for the bins to be returned.

    • Optionalpolicy: null | policy.ReadPolicy

      The Read Policy to use for this command.

    Returns Promise<AerospikeRecord>

    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()
    })
    })
    })
  • Parameters

    • key: KeyOptions

      The key of the record.

    • bins: string[]

      A list of bin names for the bins to be returned.

    • callback: TypedCallback<AerospikeRecord>

      The function to call when the command completes with the results of the command; if no callback function is provided, the method returns a Promise instead.

    Returns void

  • Parameters

    • key: KeyOptions

      The key of the record.

    • bins: string[]

      A list of bin names for the bins to be returned.

    • policy: null | policy.ReadPolicy

      The Read Policy to use for this command.

    • callback: TypedCallback<AerospikeRecord>

      The function to call when the command completes with the results of the command; if no callback function is provided, the method returns a Promise instead.

    Returns void

  • 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.

    Parameters

    • n: number

    Returns this

    v0.3.5

  • Set maximum reads/writes per second limits for a role. If a quota is zero, the limit is removed. Quotas require server security configuration "enable-quotas" to be set to true.

    Parameters

    • roleName: string

      role name

    • readQuota: number

      maximum reads per second limit, pass in zero for no limit.

    • writeQuota: number

      maximum writes per second limit, pass in zero for no limit.

    • Optionalpolicy: null | policy.AdminPolicy

      Optional AdminPolicy.

    Returns void

    const Aerospike = require('aerospike')

    function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
    }

    ;(async function () {
    let client
    try {
    client = await Aerospike.connect({
    hosts: '192.168.33.10:3000',
    policies: {
    write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
    },
    // Must have security enabled in server configuration before user and password configurations can be used.
    user: 'admin',
    password: 'admin'
    })
    // Quotas must be enabled in the server configurations for quotas to be set.
    client.setQuotas("Engineer", 200, 300)
    // Must wait a short length of time for the privilegee to be granted.
    await wait(5)
    let role = await client.queryRole("Engineer")
    console.log(role)
    } catch (error) {
    console.error('Error:', error)
    process.exit(1)
    } finally {
    if (client) client.close()
    }
    })()
  • Set IP address whitelist for a role. If whitelist is null or empty, remove existing whitelist from role.

    Parameters

    • roleName: string

      role name

    • whitelist: null | string[]

      Optional list of allowable IP addresses assigned to role. IP addresses can contain wildcards (ie. 10.1.2.0/24).

    • Optionalpolicy: null | policy.AdminPolicy

      Optional AdminPolicy.

    Returns void

    const Aerospike = require('aerospike')

    function wait (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
    }

    ;(async function () {
    let client
    try {
    client = await Aerospike.connect({
    hosts: '192.168.33.10:3000',
    policies: {
    write : new Aerospike.WritePolicy({socketTimeout : 1, totalTimeout : 1}),
    },
    // Must have security enabled in server configuration before user and password configurations can be used.
    user: 'admin',
    password: 'admin'
    })
    // Quotas must be enabled in the server configurations for quotas to be set.
    client.setWhitelist("Engineer", ["172.17.0.2"])
    // Must wait a short length of time for the privilegee to be granted.
    await wait(5)
    let role = await client.queryRole("Engineer")
    console.log(role)
    } catch (error) {
    console.error('Error:', error)
    process.exit(1)
    } finally {
    if (client) client.close()
    }
    })()
  • Returns runtime stats about the client instance.

    Returns Stats

    Client Stats

    v3.8.0

    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.

    Parameters

    • ns: string

      Required namespace.

    • set: null | string

      Optional set name. Set to null to delete all sets in namespace.

    • beforeNanos: number

      Optionally delete records before given last update time. Units are in nanoseconds since unix epoch (1970-01-01). If specified, the value must be before the current time. Pass in 0 to delete all records in namespace/set regardless of last udpate time.

    • Optionalpolicy: null | policy.InfoPolicy

      The Info Policy to use for this command.

    Returns Promise<void>

    A Promise that resolves when the truncate is complete.

    This method is many orders of magnitude faster than deleting records one at a time. It requires server 3.12 or later.

  • Parameters

    Returns void

  • Parameters

    • ns: string

      Required namespace.

    • set: null | string

      Optional set name. Set to null to delete all sets in namespace.

    • callback: TypedCallback<void>

    Returns void

  • Parameters

    • ns: string

      Required namespace.

    • set: null | string

      Optional set name. Set to null to delete all sets in namespace.

    • beforeNanos: number

      Optionally delete records before given last update time. Units are in nanoseconds since unix epoch (1970-01-01). If specified, the value must be before the current time. Pass in 0 to delete all records in namespace/set regardless of last udpate time.

    • callback: TypedCallback<void>

    Returns void

  • Parameters

    • ns: string

      Required namespace.

    • set: null | string

      Optional set name. Set to null to delete all sets in namespace.

    • beforeNanos: number

      Optionally delete records before given last update time. Units are in nanoseconds since unix epoch (1970-01-01). If specified, the value must be before the current time. Pass in 0 to delete all records in namespace/set regardless of last udpate time.

    • policy: null | policy.InfoPolicy

      The Info Policy to use for this command.

    • callback: TypedCallback<void>

    Returns void

  • Registers a UDF module with the database cluster.

    Parameters

    • udfPath: string

      The file path to the Lua script to load into the server.

    • OptionaludfType: null | LUA

      Language of the UDF script. Lua is the default and only supported scripting language for UDF modules at the moment; ref. language.

    • Optionalpolicy: null | policy.InfoPolicy

      The Info Policy to use for this command.

    Returns Promise<Job<JobInfoResponse>>

    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()
    })
    })
    })
  • Parameters

    • udfPath: string

      The file path to the Lua script to load into the server.

    • Optionalpolicy: null | policy.InfoPolicy

      The Info Policy to use for this command.

    Returns Promise<Job<JobInfoResponse>>

    A Promise that resolves to a Job instance.

  • Parameters

    • udfPath: string

      The file path to the Lua script to load into the server.

    • callback: TypedCallback<Job<JobInfoResponse>>

      The function to call when the command completes with the result of the command.

    Returns void

  • Parameters

    • udfPath: string

      The file path to the Lua script to load into the server.

    • udfType: null | LUA

      Language of the UDF script. Lua is the default and only supported scripting language for UDF modules at the moment; ref. language.

    • callback: TypedCallback<Job<JobInfoResponse>>

      The function to call when the command completes with the result of the command.

    Returns void

  • Parameters

    • udfPath: string

      The file path to the Lua script to load into the server.

    • policy: null | policy.InfoPolicy

      The Info Policy to use for this command.

    • callback: TypedCallback<Job<JobInfoResponse>>

      The function to call when the command completes with the result of the command.

    Returns void

  • Parameters

    • udfPath: string

      The file path to the Lua script to load into the server.

    • udfType: null | LUA

      Language of the UDF script. Lua is the default and only supported scripting language for UDF modules at the moment; ref. language.

    • policy: null | policy.InfoPolicy

      The Info Policy to use for this command.

    • callback: TypedCallback<Job<JobInfoResponse>>

      The function to call when the command completes with the result of the command.

    Returns void

  • Removes a UDF module from the cluster.

    Parameters

    • udfModule: string

      The basename of the UDF module, without the local pathname but including the file extension (".lua").

    • Optionalpolicy: null | policy.InfoPolicy

      The Info Policy to use for this command.

    Returns Promise<Job<JobInfoResponse>>

    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()
    })
    })
    })
  • Parameters

    • udfModule: string

      The basename of the UDF module, without the local pathname but including the file extension (".lua").

    • callback: TypedCallback<Job<JobInfoResponse>>

      The function to call when the command completes with the result of the command.

    Returns void

  • Parameters

    • udfModule: string

      The basename of the UDF module, without the local pathname but including the file extension (".lua").

    • policy: policy.InfoPolicy

      The Info Policy to use for this command.

    • callback: TypedCallback<Job<JobInfoResponse>>

      The function to call when the command completes with the result of the command.

    Returns void

  • Updates log settings for the client.

    Parameters

    • logConfig: Log

      A Log instance containing a log level and/or a file descriptor. For more info, see Log

    Returns void

  • Experimental

    Listens once to the abort event on the provided signal.

    Listening to the abort event on abort signals is unsafe and may lead to resource leaks since another third party with the signal can call e.stopImmediatePropagation(). Unfortunately Node.js cannot change this since it would violate the web standard. Additionally, the original API makes it easy to forget to remove listeners.

    This API allows safely using 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]();
    }
    }

    Parameters

    • signal: AbortSignal
    • resource: ((event: Event) => void)
        • (event): void
        • Parameters

          • event: Event

          Returns void

    Returns Disposable

    Disposable that removes the abort listener.

    v20.5.0

  • Returns 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] ]
    }

    Parameters

    • emitter: EventEmitter<DefaultEventMap> | EventTarget
    • name: string | symbol

    Returns Function[]

    v15.2.0, v14.17.0

  • Returns 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
    }

    Parameters

    • emitter: EventEmitter<DefaultEventMap> | EventTarget

    Returns number

    v19.9.0

  • A class method that returns the number of listeners for the given eventName registered on the given emitter.

    import { EventEmitter, listenerCount } from 'node:events';

    const myEmitter = new EventEmitter();
    myEmitter.on('event', () => {});
    myEmitter.on('event', () => {});
    console.log(listenerCount(myEmitter, 'event'));
    // Prints: 2

    Parameters

    • emitter: EventEmitter<DefaultEventMap>

      The emitter to query

    • eventName: string | symbol

      The event name

    Returns number

    v0.9.12

    Since v3.2.0 - Use listenerCount instead.

  • import { on, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    });

    for await (const event of on(ee, 'foo')) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
    }
    // Unreachable here

    Returns an AsyncIterator that iterates eventName events. It will throw if the EventEmitter emits 'error'. It removes all listeners when exiting the loop. The value returned by each iteration is an array composed of the emitted event arguments.

    An AbortSignal can be used to cancel waiting on events:

    import { on, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ac = new AbortController();

    (async () => {
    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    });

    for await (const event of on(ee, 'foo', { signal: ac.signal })) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
    }
    // Unreachable here
    })();

    process.nextTick(() => ac.abort());

    Use the close option to specify an array of event names that will end the iteration:

    import { on, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    ee.emit('close');
    });

    for await (const event of on(ee, 'foo', { close: ['close'] })) {
    console.log(event); // prints ['bar'] [42]
    }
    // the loop will exit after 'close' is emitted
    console.log('done'); // prints 'done'

    Parameters

    • emitter: EventEmitter<DefaultEventMap>
    • eventName: string | symbol
    • Optionaloptions: StaticEventEmitterIteratorOptions

    Returns AsyncIterator<any[], any, any>

    An AsyncIterator that iterates eventName events emitted by the emitter

    v13.6.0, v12.16.0

  • Parameters

    • emitter: EventTarget
    • eventName: string
    • Optionaloptions: StaticEventEmitterIteratorOptions

    Returns AsyncIterator<any[], any, any>

  • Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

    This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event semantics and does not listen to the 'error' event.

    import { once, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ee = new EventEmitter();

    process.nextTick(() => {
    ee.emit('myevent', 42);
    });

    const [value] = await once(ee, 'myevent');
    console.log(value);

    const err = new Error('kaboom');
    process.nextTick(() => {
    ee.emit('error', err);
    });

    try {
    await once(ee, 'myevent');
    } catch (err) {
    console.error('error happened', err);
    }

    The special handling of the 'error' event is only used when events.once() is used to wait for another event. If events.once() is used to wait for the 'error' event itself, then it is treated as any other kind of event without special handling:

    import { EventEmitter, once } from 'node:events';

    const ee = new EventEmitter();

    once(ee, 'error')
    .then(([err]) => console.log('ok', err.message))
    .catch((err) => console.error('error', err.message));

    ee.emit('error', new Error('boom'));

    // Prints: ok boom

    An AbortSignal can be used to cancel waiting for the event:

    import { EventEmitter, once } from 'node:events';

    const ee = new EventEmitter();
    const ac = new AbortController();

    async function foo(emitter, event, signal) {
    try {
    await once(emitter, event, { signal });
    console.log('event emitted!');
    } catch (error) {
    if (error.name === 'AbortError') {
    console.error('Waiting for the event was canceled!');
    } else {
    console.error('There was an error', error.message);
    }
    }
    }

    foo(ee, 'foo', ac.signal);
    ac.abort(); // Abort waiting for the event
    ee.emit('foo'); // Prints: Waiting for the event was canceled!

    Parameters

    • emitter: EventEmitter<DefaultEventMap>
    • eventName: string | symbol
    • Optionaloptions: StaticEventEmitterOptions

    Returns Promise<any[]>

    v11.13.0, v10.16.0

  • Parameters

    • emitter: EventTarget
    • eventName: string
    • Optionaloptions: StaticEventEmitterOptions

    Returns Promise<any[]>

  • import { setMaxListeners, EventEmitter } from 'node:events';

    const target = new EventTarget();
    const emitter = new EventEmitter();

    setMaxListeners(5, target, emitter);

    Parameters

    • Optionaln: number

      A non-negative number. The maximum number of listeners per EventTarget event.

    • Rest...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]

      Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, n is set as the default max for all newly created {EventTarget} and {EventEmitter} objects.

    Returns void

    v15.4.0

MMNEPVFCICPMFPCPTTAAATR