Get NodeCopter data from client just once? - node.js

I would like to get the data from a client (AR.Drone 2.0) just once and them store it in a variable to be printed. I have used:
client.on('navdata', console.log);
however, when I execute this command data is printed more than once and I have to stop the script to stop this process. How can I get the data just once and store it in a variable.

Client object inherits EventEmitter, so you should be able to use once() to listen for navdata event only once. To store the emitted value to a variable you can do something like:
var _navData;
// ...
client.once('navdata', function (navData) {
_navData = navData;
});
Update
Regarding to your comment, I suggest you to declare a function that gets a navdata object as an argument and pass that function to client.once():
var doSomethingWithNavData = function doSomethingWithNavData(navData) {
console.log(navData);
// do what ever you want to do with navData...
}
client.once('navdata', doSomethingWithNavData);

There are two EventEmitter methods for adding listeners: .on() and .once().
.on() actively listens and catches events until .removeListener() or .removeAllListeners() are called to remove the listener.
.once() listens for the next event and removes itself automatically (effectively running once), unless .removeListener() or .removeAllListeners() are called to remove it before it does.

Related

unable to remove listener from mongodb change stream 'change' event

I figured the mongodb change stream extends the EventEmitter class, so I tried removing events I installed by using the removeListener function.
After calling removeListener on the change stream it still fired on change. May be I'm just using the wrong function reference when removing, but I can not see how.
I found out removeAllListeners does remove the attached listener. But I need to be in control what listener to remove.
const change_listener = (change) => {
console.log(change_stream.listenerCount("change"))
change_stream.removeListener("change", change_listener)
console.log(change_stream.listenerCount("change"))
}
change_stream.on("change", change => change_listener(change))
should output
1
0
but it outputs
1
1
and the listener goes on listening.
Using .once instead of .on only helps half the way. I would still need removeListener because I need to be able to cancel the listener early.
The problem is due to the function you are removing.
This should work:
const change_listener = (change) => {
console.log(change_stream.listenerCount("change"))
change_stream.removeListener("change", change_listener)
console.log(change_stream.listenerCount("change"))
}
change_stream.on("change", change_listener)
Note that change => change_listener(change) is a function and it is different from change_listener

Destroy socket before or after removing it from array

In my node.js application I have a collection of client sockets as an array. When a communication error occurs, I simply call destroy on the socket.
My question is: should I destroy the socket before or after removing it from the array? The documentation doesn't say much.
var clientSockets = []
var destroySocketBefore = function(socket) {
socket.destroy()
var socketIdx = clientSockets.indexOf(socket)
if (socketIdx > -1) {
clientSockets.splice(socketIdx, 1)
}
}
var destroySocketAfter = function(socket) {
var socketIdx = clientSockets.indexOf(socket)
if (socketIdx > -1) {
clientSockets.splice(socketIdx, 1)
}
socket.destroy()
}
In the case of destroySocketBefore, I am not sure if the socket will be found in the array if I destroy it before searching for it, so there is a possibility that array still incorporates invalid sockets in subsequent logic.
In the case of destroySocketAfter, I am not sure if calling destroy on a socket that was removed from array will have the desired result. Is there a possibility that the system will delete the socket object after splicing the array, so sometimes I get to call destroyon a null object.
I tested and it seems that both methods work as there is no difference between them, so I am not sure which method is the correct one.
Either solution is valid and the two are effectively the same. The destroyed socket will get removed no matter what since there are no race conditions or anything like that (since javascript execution in node all happens on the same thread).
splice will only remove the socket from an user defined array and will have no effect to it been closed, therefore the second method is the best option according to your answers.

socket.io-emiiter on Redis has to be reinitialized every time to send data

Have to re-initialize socketEmitter every-time I send data, as shown below
pushNotification.pushData = function (data) {
var socketEmitter = require('socket.io-emitter')(config.redis);
socketEmitter = socketEmitter.of('/webSocket');
socketEmitter.in(data.orgId).emit(data.event, data.msg);
}
If I initialize socketEmitter globally and try to reuse it inside pushData function, the pushData function works only for the first time.
socket.io-emitter resets the namespace after every emit.
Fixed the issue by resetting the namespace for every data sent.

How to remove a listener in chrome.webRequest API in dart?

Related to `chrome.webRequest.onBeforeRequest.removeListener`? -- How to stop a chrome web listener, I am trying to deregister a listener using dart:js
After invoking onBeforeRequest.callMethod('removeListener', [callback]); I notice that the listener is still being called. Furthermore, directly after adding a listener the hasListenerreturns false (even thought the listener is being registered).
var callback = (map) { /* some code */ };
var filter = new JsObject.jsify({"key": "value"});
var opt_extraInfoSpec = new JsObject.jsify(["extra opt"]);
// chrome.webRequest.onBeforeRequest.addListener
JsObject onBeforeRequest = context['chrome']['webRequest']['onBeforeRequest'];
onBeforeRequest.callMethod('addListener', [callback, filter, opt_extraInfoSpec]);
Logger.root.fine('main(): does callback exist: ${onBeforeRequest.callMethod('hasListener', [callback])}');
It seems to be necessary to follow 100% the dart:js recommendations how to use a dart Function in the javascript environment. I guess my problem was that the original dart dynamic function is wrapped automatically in a proxy. Hence the callMethod for addListener used a different proxy object then the callMethod for hasListener, even thought both of them were based on the same original dart object (i.e. callback).
The solution is to use the JsFunction and define the callback as following:
var callback = new JsFunction.withThis((that, map) { /* some code */ });

Node.js event scope?

I would like to use an event in node.js to execute some code; my question is, what is the scope of the invoked event code? Specifically, does it share the scope of the event invoker, or is it "isolated"? I know that I can pass parameters to the code invoked on the event to achieve a similar effect, but ideally I'd like to have the invoking scope available.
The event is tied to the scope of the invoker. i.e. an EventEmitter exported from a module, can only be used to listen for events emitted from that same EventEmitter.
Nodejs EventEmitter - Define scope for listener function
When you emit an event, you put it into a queue to be processed later by the node event system. Any variables from the scope where the event is emitted must be passed to emit as arguments. When node takes that event and triggers all bound callbacks, that happens under both a distinct "clean" scope and a distinct "clean" stack. (Side note, this is why stack traces in node can be a nuisance for debugging).
var events = require('events');
var myEmitter = new events.EventEmitter();
function closure1(word, number) {
function closure2(animal, vegetable) {
myEmitter.emit('hey', word, number, animal, vegetable, 43);
}
closure2("horse", "carrot");
}
myEmitter.on('hey', function (word, number, animal, vegetable, anotherNumber) {
console.log('hey event fired with', word, number, animal, vegetable, anotherNumber);
});
closure1("table", 42);
When you run that, it will print "hey event fired with table 42 horse carrot 43".
see the node.js docs on emitter.emit(event, [arg1], [arg2], [...]

Resources