Create a client for connecting to an OpenIAP flow instace. By default it loads the apiurl from environment variable apiurl, grpcapiurl or wscapiurl You can supply username and password in the URL ( remember this needs to e URL encoded ) or you can supply a JWT token in the jwt environment variable or as the second parameter to the constructor.
You can connect using one of these protocols
grpc://host.name:port
For docker or kubernetes deployments this is usually the main domain prefixed with grpc.
for instance if your main domain is app.openiap.io
then the grpc url would be grpc://grpc.app.openiap.io:443
For developer installations, the grpc url would be grpc://localhost:50051
wss://app.openiap.io
or ws://localhost.openiap.io
pipe://localhost/testpipe
tcp://localhost.openiap.io:8080
https://app.openiap.io/api/v2
or http://localhost.openiap.io/api/v2
Connect to OpenIAP flow instance
const { openiap } = require("@openiap/nodeapi");
client.connect().then(async client=> {
console.log("Connected")
const result = await client.Query({ query: { "_type": "test" } });
console.log(result);
client.Close();
}).catch(err => {
console.log("Failed to connect: " + err)
}
Connect to OpenIAP using a connection string.
const { openiap } = require("@openiap/nodeapi");
async function main() {
const client = new openiap("grpc://grpc.app.openiap.io:443");
await client.connect();
const user = client.Signin({username: "henrik", password: "SuperSecret"});
}
main();
Alternatively we can supply credentials in the connection string, then we do not need to call Signin
const { openiap } = require("@openiap/nodeapi");
async function main() {
const client = new openiap("grpc://henrik:SuperSecret@grpc.app.openiap.io:443");
await client.connect();
}
main();
By default we read from environment variable apiurl, grpcapiurl or wscapiurl but can be overriden here
By default we read from environment variable jwt but can be overriden here
Define client type when authenticating toward the server
If false, the client will never give up trying to connect to the server, if true, will give up after 17 seconds
The internal client object
Define if connected to server
Define if we are trying to (re)connect
Private
defaltqueueThe JWT used when authenticating to the server
Private
loginrejectPrivate
loginresolvePrivate
pingerhandlePrivate
queuecallbacksPrivate
queuesPrivate
reconnectmsIf connected, are we also signed in or is server waiting on use to authenticate
The URL used when connecting to the server
Define the version of the client sent to the server
Private
watchidsStatic
Readonly
captureStatic
captureSets or gets the default captureRejection value for all emitters.
Static
defaultStatic
Readonly
errorThis symbol shall be used to install a listener for only monitoring 'error'
events. Listeners installed using this symbol are called before the regular
'error'
listeners are called.
Installing a listener using this symbol does not change the behavior once an
'error'
event is emitted, therefore the process will still crash if no
regular 'error'
listener is installed.
Create a new workitem queue. Workitem queues are registered in the wiq collection.
AddWorkItemQueueOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Run an mongodb aggregation pipeline toward the OpenIAP flow database. See https://docs.mongodb.com/manual/aggregation/ for more information
An array of documents matching the aggregation pipeline
https://docs.mongodb.com/manual/aggregation/
Get the count of all documents with type "test" from entities collection
const result = await client.Aggregate({ collectionname: "entities", aggregates: [{ "$match": { "_type": "test" } }, { "$count": "count" }] });
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Getting the count of documents in a collection can be done using this function. Leave query empty to get the total count of documents in the collection.
The number of documents matching the query
Get the count of documents with type "test" from entities collection
const result = await client.Count({ collectionname: "entities", query: { "_type": "test" } });
Get the total number of documents in the entities collection
const result = await client.Count({ collectionname: "entities" });
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Create a collection removing all data from the collection. Only users with admin rights can Create collections.
CreateCollectionOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Return the console output of an running agent, can be in docker, kubernetes or running remote. Requires invoke permission on agent
Returns the index name
CreateIndexOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Old command used by nodered "Workflow in" and "assign" nodes for creating a new workflow instance.
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Run custom commands not defined in the protocol yet. This is how new functioanlly is added and tested, before it is finally added to the offical proto3 protocol.
If command has a result, this will be returned as a string. This will most likely need to be parser as JSON
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Remove an agent if running. Docker and Kubernetes only. Removes instance on docker, remove deployment, ingress and other resources on Kubernetes Requires delete permission on agent
void
DeleteAgentOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Remove an agent pod, found with GetAgentPods. Docker and Kubernetes only. Requires invoke permission on agent
void
DeleteAgentPodOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Delete many documents from a collection based on a query. Will return 0 if no documents are deleted.
The number of deleted documents
Delete all documents with name "find me" in entities collection
const result = await client.DeleteMany({ query: { name: "find me" } });
console.log("Deleted " + result + " documents");
Delete all documents with type "invoice" in entities collection
const result = await client.DeleteMany({ query: { _type: "invoice" } });
console.log("Deleted " + result + " documents");
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Delete one document from a collection. Will throw an error if document does not exist or you don't have the right permissions. if recursive is set to true, all asssoicated documents will be deleted as well. Currently only user and customer objects in the "users" collection are supported for recursive deletion.
Number of deleted documents (will always be 1)
Delete a document with id "643917fb153b7c2c1466fb21" in entities collection
const result = await client.DeleteOne({ id: "643917fb153b7c2c1466fb21" } });
console.log("Deleted " + result + " documents");
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Delete an agent Package. Removes the associated file and then delete te package from the agents collection. Requires delete permission on the Package
void
DeletePackageOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Delete a workitem queue. Workitem queues are registered in the wiq collection. If queue has workitems in it, the request will fail, unless purge is set to true.
DeleteWorkItemQueueOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Delete one workitem and all associated files from a workitem queue.
Delete a workitem
client.DeleteWorkitem({ id: "64366f12cffb7419a89d5e10" });
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Finds the distinct values for a specified field across a single collection
returns the results in an array
Get the distinct name of all documents with type "test"
const result = await client.Distinct({ collectionname: "entities", field: "name", query: { "_type": "test" } });
Get the distinct types in the entities collection
const result = await client.Distinct({ collectionname: "entities", field: "_type" });
DistinctOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Download a file from OpenIAP flow database, using the file id or file name. This uses streams to download file content, and is therefore not supported using REST interface.
Drop a collection removing all data from the collection. Only users with admin rights can drop collections.
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Drop a MongoDB index from a collection. Requires admins permission
void
DropIndexOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Create a collection removing all data from the collection. Only users with admin rights can Create collections.
EnsureCustomerOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Query a collection for data and return the first document
a document matching the query
Get the first document with type "test" from entities collection
const result = await client.FindOne({ query: { "_type": "test" } });
Get the first document with type "test" from entities collection and only return the name field
const result = await client.FindOne({ collectionname: "entities", query: { "_type": "test" }, projection: { "name": 1 } });
Get the first document with type "test" from entities collection and only return the name field and order by name
const result = await client.FindOne({ collectionname: "entities", query: { "_type": "test" }, projection: { "name": 1 }, orderby: { "name": 1 } });
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Return the console output of an running agent, can be in docker, kubernetes or running remote. Requires invoke permission on agent
Return pods console output
GetAgentLogOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Return a list of pods for an running agent. Docker and Kubernetes only. Requires invoke permission on agent
Array of pods
GetAgentPodsOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
By default OpenIAP will keep history information about all data in the database. This function will try and reconstruct the document at it was at a given version. This can be used to restore data to a previous state or even restore deleted data.
The reconstructed document
Get the document with id "643917fb153b7c2c1466fb21" from entities collection at version 1
const result = await client.GetDocumentVersion({ id: "643917fb153b7c2c1466fb21", version: 1 });
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Bulk insert multiple documents into a collection, this is faster than using InsertOne multiple times.
When skipresults is false, will return an array of the documents that was created, including the _id field
Insert multiple documents with type "test" into entities collection
const result = await client.InsertMany({ collectionname: "entities", items: [{ "_type": "test", name: "find me" }, { "_type": "test", name: "find me too" }] });
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Insert a document into a collection
The object that was created, including the _id field
Insert a document with type "test" into entities collection
const result = await client.InsertOne({ collectionname: "entities", item: { "_type": "test", name: "find me" } });
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Will match all documents toward a collection using the uniqeness parameters ( _id if left out ) and update it if it exists, or insert it if it does not exist. Will trhow an error if more than one document exists that matches the uniqeness parameters. This will use bulk operations to speed up the process.
The updated or inserted documents including the _id field
Insert or update multiple invoice documents in entities collection
const invoices = [{ "_type": "invoice", invoiceid: "1234", name: "find me" }, { "_type": "invoice", invoiceid: "1235", name: "find me too" }]
const result = await client.InsertOrUpdateMany({ items: invoices, uniqeness: ["invoiceid"] });
console.log("Inserted document with id: " + result[0]._id + " and name: " + result[0].name);
console.log("Inserted document with id: " + result[1]._id + " and name: " + result[1].name);
const same_invoice = [{ "_type": "invoice", invoiceid: "1234", name: "Can you still find me?"}, { "_type": "invoice", invoiceid: "1235", name: "Can you still find me too?"}]
const updated = await client.InsertOrUpdateMany({ items: same_invoice, uniqeness: ["invoiceid"] });
console.log("Updated document with id: " + updated[0]._id + " and new name: " + updated[0].name);
console.log("Updated document with id: " + updated[1]._id + " and new name: " + updated[1].name);
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Will match a document in a collection on the uniqeness parameters ( _id if left out ) and update it if it exists, or insert it if it does not exist. Will trhow an error if more than one document exists that matches the uniqeness parameters.
The updated or inserted document including the _id field
Insert or update a document with invoiceid "1234" in entities collection
const result = await client.InsertOrUpdateOne({ item: { "_type": "invoice", invoiceid: "1234", name: "find me" }, uniqeness: ["invoiceid"] });
console.log("Inserted document with id: " + result._id + " and name: " + result.name);
const same_invoice = { "_type": "invoice", invoiceid: "1234", name: "Can you still find me?"}
const updated = await client.InsertOrUpdateOne({ item: same_invoice, uniqeness: ["invoiceid"] });
console.log("Updated document with id: " + updated._id + " and new name: " + updated.name);
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Invoke an OpenRPA workflow on a robot or a role with multiple robots in. At writing, this command is only supprted using OpenAPI endpoint
null if rpc is false, else the result of the workflow if workflow has any inout/out parameters
InvokeOpenRPAOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Returns a list of all known collections. By default filtering out history collectins.
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Used internally to send a ping message to server, to keep the connection alive. Only used if server require pings, or if the client is configured to send pings using DoPing
Pop an item of a workitem queue. An items aviailable in the queue will be determined by it's status, retry time and runat time steamp. If multiple items are available, the items will be fatched based on each wrkitem's priority field.
If no workitem is available, this will return null.
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Push a workitem to a workqueue. Workitem can be processed by a worker after calling PopWorkitem
Returns the workitem that was pushed, including the workitem id
Push a workitem to myworkqueue
const workitem = await client.PushWorkitem({ wiq: "myworkqueue", payload: { "hello": "world" } });
console.log("Pushed workitem with id " + workitem._id);
Push a workitem with a file to myworkqueue
import * as path from 'path';
import * as fs from "fs";
import * as pako from 'pako';
// ....
const filepath = "/path/data.csv";
const filename = path.basename(filepath);
const workitem = await client.PushWorkitem({
payload: {"name": "test " + filename}, wiq: "q2", name: "file test " + filename,
files: [{ _id:"", filename, compressed: true, file: pako.deflate(fs.readFileSync(filepath, null)) }]});
console.log("Pushed workitem with id " + workitem._id);
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Push multiple workitems to a workqueue. Workitems can be processed by a worker after calling PopWorkitem
an array of workitems that was pushed, including the workitem id's
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Query a collection for data
an array of documents matching the query
Get all documents with type "test" from entities collection
const result = await client.Query({ query: { "_type": "test" } });
Get all documents with type "test" from entities collection and only return the name field
const result = await client.Query({ collectionname: "entities", query: { "_type": "test" }, projection: { "name": 1 } });
Get all documents with type "test" from entities collection and only return the name field and order by name
const result = await client.Query({ collectionname: "entities", query: { "_type": "test" }, projection: { "name": 1 }, orderby: { "name": 1 } });
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Send message to queue or exchange. If recevied sends a reply back, set rpc = true to recevied response as return value. Be aware, right now there is no timeout on the wait, so if recevier never sends a reply it will hang for ever
If rpc is trye, will return the reply from the queue. If rpc is false, will return null when server has received the message
Send message to myqueue and wait for reply, then dump the result to console
const result = await client.QueueMessage({ queuename: "myqueue", data: { "hello": "world" } }, true);
console.log("result from queue " + JSON.stringify(result, null, 2));
Send message to myexchange
await client.QueueMessage({ exchangename: "myexchange", data: { "hello": "world" } }, false);
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Register an exchange and a message queue and consume it. Exchange's are registered in the mq collection. This uses streams to notify client about messages, and is therefore not supported using REST interface.
Returns the queue name, used to consume the exchange. Use this when unregistering the exchange with UnRegisterQueue
const queuename = await client.RegisterExchange({ exchange: "myexchange" }, (msg, payload, user, jwt) => {
console.log(JSON.stringify(payload, null, 2));
});
console.log("registered exchange myexchange and is consuming it using queue " + queuename);
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Register and consume a Message Queue. Queues are registered in the mq collection. If no queue name is provided, a random queue name is generated. This uses streams to notify client about messages, and is therefore not supported using REST interface.
Returns the queue name. Use this name to send messages to the queue. Also use this to unregister the queue with UnRegisterQueue
const queuename = await client.RegisterQueue({ queuename: "myqueue" }, (msg, payload, user, jwt) => {
console.log(JSON.stringify(payload, null, 2));
if(payload == null) payload = {}
payload.result = true
// If returning a onject, it will be sent back to the sender of the message, if caller requested a response using rpc = true.
return payload;
});
console.log("registered queue " + queuename);
By default we use crendetials from the connection string or from jwt environment variable. But you can also call Signin to login with a username and password or with a jwt token. This function can also be used to validate credentials without changing the current credentials by setting validateonly to true.
Start an agent inside Docker or Kubernetes Requires invoke permission on agent
void
StartAgentOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Stop an agent running inside Docker or Kubernetes Requires invoke permission on agent
void
StopAgentOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Tell server to close queue and stop receving message from the queue ( or queue consuming an exchange )
const queuename = await client.RegisterExchange({ exchange: "myexchange" }, async (msg, payload, user, jwt) => {
console.log(JSON.stringify(payload, null, 2));
await client.UnRegisterQueue({ queuename: queuename });
console.log("unregistered queue " + queuename);
});
console.log("registered exchange myexchange and is consuming it using queue " + queuename);
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Unregister a change stream ( watch ) created with Watch to stop receiving notifications from the watch.
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Run an update command on a collection, to update one or more documents matching a query. See https://docs.mongodb.com/manual/reference/operator/update/ for more information on the update operators.
An object with update statistics see UpdateResult
https://docs.mongodb.com/manual/reference/operator/update/
Update all documents with type "test" in entities collection
const result = await client.UpdateDocument({ collectionname: "entities", query: { "_type": "test" }, document: { "$set": { "name": "find me" } } });
console.log("Updated " + result.matchedCount + " documents");
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Update ( replace ) an existing document in a collection. Any fields that starts with underscoore will be preserved. This is to prevent the system from overwriting fields that are used by the system. So if you update a document but leave out any of the existing _ fields, they will be added back to the document.
Returns the document that was updated
Update a document with type "test" in entities collection
const result = await client.InsertOne({ item: { "_type": "test", name: "find me" } });
console.log("Inserted document with id: " + result._id + " and name: " + result.name);
result.name = "Can you still find me?"
const updated = await client.UpdateOne({ item: result });
console.log("Updated document with id: " + updated._id + " and name: " + updated.name);
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Create a new workitem queue. Workitem queues are registered in the wiq collection. To delete all items from qyueue, set purge to true.
UpdateWorkItemQueueOptions
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Update an existing workitem. Workitem can be fetched using PopWorkitem. Use this to update the status of a workitem. You can also update the payload, and update or add files to the workitem.
Returns the updated workitem
Update a workitem
const workitem = await client.PopWorkitem({ wiq: "purchase_orders" }); // Will update the workitem state to processing
if(workitem == null) return;
await new Promise(resolve => setTimeout(resolve, 1000)); // simulate processing
if(workitem.payload == null) workitem.payload = {}
workitem.payload.transaction = "ID45434" // update payload
workitem.status = "successful" // must be successful, processing or retry
await client.UpdateWorkitem({ workitem }); // update workitem
console.log("Updated workitem with id " + workitem._id);
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Upload a file to OpenIAP flow database. This uses streams to download file content, and is therefore not supported using REST interface.
Server response, including the file id
Upload test.txt from current folder to OpenIAP flow database
const res = await client.UploadFile({ filename: "test.txt" });
console.log("file upladed with id " + res.id);
Register a change stream ( watch ) on a collection. Use paths to narrow the scope of the watch. The callback will be called for each document that matches the paths when ever it is inserted, updated or deleted from the database This uses streams to notify client about changes, and is therefore not supported using REST interface.
server id assigned to the watch. Used with UnWatch to stop receiving notifications from the watch.
const watchid = await db.Watch({ collectionname: "entities", paths: ["$.[?(@._type == 'test')]"] }, (operation, document) => {
console.log(operation + " on " + document.name);
});
Message priority, the higher the number the higher the priority. Default is 2, 3 or higher requeires updates to server configuration
Alias for emitter.on(eventName, listener)
.
v0.1.26
Rest
...args: any[]Private
cliPrivate
cliPrivate
cliOverride this function to get notified when the client receives a message from the server. This will only be called for messages that are not handled by the client it self. Using EventMitter is also possible .on("message", (client, command, message) => {})
Returns the User object if login was successful, otherwise throws an error
var client = new openiap();
client.connect().then(async (user) => {
console.log("Logged in as " + user.username);
}).catch((err) => {
console.log("Failed to login: " + err);
});
Should be left out or used as true. Is used internally for controlling retry logic
Synchronously calls each of the listeners registered for the event namedeventName
, in the order they were registered, passing the supplied arguments
to each.
Returns true
if the event had listeners, false
otherwise.
const EventEmitter = require('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
v0.1.26
Rest
...args: any[]Returns an array listing the events for which the emitter has registered
listeners. The values in the array are strings or Symbol
s.
const EventEmitter = require('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) ]
v6.0.0
Returns the current max listener value for the EventEmitter
which is either
set by emitter.setMaxListeners(n)
or defaults to defaultMaxListeners.
v1.0.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] ]
v0.1.26
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. Theemitter.prependListener()
method can be used as an alternative to add the
event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
v0.1.101
The name of the event.
The callback function
Rest
...args: any[]Override this function to add logic executed when the client has connected to the server. If credentails has been set, the client will automatically login before calling this function Using EventMitter is also possible using client.on("connected", (client) => {})
using onConnected override
var client = new openiap();
client.onConnected = (client) => {
console.log("Connected to server");
}
client.connect();
using EventEmitter. Remember to remove the listener when done to avoid memory leaks
var client = new openiap();
client.on("connected", (client) => {
console.log("Connected to server");
});
client.connect();
Override this function to add logic executed when the client has disconnected from the server. Using EventMitter is also possible .on("disconnected", (client, error) => {})
using onConnected override
var client = new openiap();
client.onDisconnected = (client, err) => {
console.log("Disconnected from server");
}
client.connect();
using EventEmitter. Remember to remove the listener when done to avoid memory leaks
var client = new openiap();
client.on("disconnected", (client, err) => {
console.log("Disconnected from server");
});
client.connect();
Return client instance that disconnected
If the disconnect was caused by an error, this will contain the error object
Adds a one-timelistener
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. Theemitter.prependOnceListener()
method can be used as an alternative to add the
event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
v0.3.0
The name of the event.
The callback function
Rest
...args: any[]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.
v6.0.0
The name of the event.
The callback function
Rest
...args: any[]Adds a one-timelistener
function for the event named eventName
to the beginning of the listeners array. The next time eventName
is triggered, this
listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the EventEmitter
, so that calls can be chained.
v6.0.0
The name of the event.
The callback function
Rest
...args: any[]Returns a copy of the array of listeners for the event named eventName
,
including any wrappers (such as those created by .once()
).
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');
v9.4.0
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.
v0.1.26
Optional
event: string | symbolRemoves the specified listener
from the listener array for the event namedeventName
.
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 anyremoveListener()
or removeAllListeners()
calls after emitting and before the last listener finishes execution
will not remove them fromemit()
in progress. Subsequent events behave as expected.
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:
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.
v0.1.26
Rest
...args: any[]By default EventEmitter
s will print a warning if more than 10
listeners are
added for a particular event. This is a useful default that helps finding
memory leaks. The emitter.setMaxListeners()
method allows the limit to be
modified for this specific EventEmitter
instance. The value can be set toInfinity
(or 0
) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter
, so that calls can be chained.
v0.3.5
Static
GetStatic
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
the emitter.
For EventTarget
s this is the only way to get the event listeners for the
event target. This is useful for debugging and diagnostic purposes.
const { getEventListeners, EventEmitter } = require('events');
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
getEventListeners(et, 'foo'); // [listener]
}
v15.2.0, v14.17.0
Static
listenerA class method that returns the number of listeners for the given eventName
registered on the given emitter
.
const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
v0.9.12
Since v3.2.0 - Use listenerCount
instead.
The emitter to query
The event name
Static
onconst { on, EventEmitter } = require('events');
(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')) {
// 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:
const { on, EventEmitter } = require('events');
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());
v13.6.0, v12.16.0
that iterates eventName
events emitted by the emitter
The name of the event being listened for
Optional
options: StaticEventEmitterOptionsStatic
onceCreates 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.
const { once, EventEmitter } = require('events');
async function run() {
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.log('error happened', err);
}
}
run();
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:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.log('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
An AbortSignal
can be used to cancel waiting for the event:
const { EventEmitter, once } = require('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!
v11.13.0, v10.16.0
Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setconst {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
v15.4.0
Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter | _DOMEventTarget)[]Generated using TypeDoc
OpenIAP