Storing value and then sending everything in Javascript - javascript

I am working in Node-red built on node js
I was trying to create one node which will store all inputs from different function node and then will send them all to next node.
in Node-RED each msg process once and it is sent and the msg process is asynchronous by property.
Documentation : http://nodered.org/docs/creating-nodes/node-js.html
This is node-RED wiring screenshot:
There are two functions going to a concatenation node
The concatenation node code is:
module.exports = function(RED) {
function LowerCaseNode(config) {
RED.nodes.createNode(this,config);
var node = this;
this.on('input', function(msg) {
var abc = [];
abc.push(msg.payload);
node.send(msg);
});
}
RED.nodes.registerType("lower-case",LowerCaseNode);
}
the output what I am getting in debug tab is:
The output I wanted in debug tab is:

Your concat node has no way of knowing which function node the incoming message came from, there is no information about the source passed with a message.
The best you could do is set a different topic field in each function node and use this to distinguish inputs.
Also this probably doen't need to be a separate node, you should be able to implement it as a function node and make use of the context variable.

Related

Getting Values out of Websocket Functions

I am working on a project which needs to get communication from C++ code to JavaScript on a webserver. Currently, I have data sending properly and it's being received but the issue is that I cant use the data outside of the inner(onmessage) function. This still works fine to overwrite elements of the webpage, but the charts I'm trying to build cant get the live data. If I put the code for the chart inside the inner function the entire program freezes and I can't get the variable out of the function for me to use it in the parent either. Right now, I just want to get the data out of the inner function so I can use it. So, is there any way for me to pull that data out of the inner function and use it in the parent function?
Here is my code:
{
var x;
var ws = new WebSocket('ws://localhost:10011/');
ws.onmessage = function(event)
{
x = event.data;
var testing = document.getElementById('InnerFunctionOutput');
testing.innerHTML = "Run Time: " + x;
}
var testing = document.getElementById('ParentFunctionOutput');
testing.innerHTML = "Run Time: " + x;
}
When I run this code the output from the inner function is the constant stream of data and the output from the parent is a constant 1. If anyone could help me find a solution, it would be greatly appreciated.
One alternative solution is to put the functions for the charts inside the websocket function. That way, I wouldn't have to get data out of the function. however, this solution has its own set of problems. I will put a link below to a thread where I ask about this alternate solution if you are interested in that part.
Plotly and Websockets
Any help would be greatly appreciated.
Thanks,
Luke
I found a solution to the problem. To get the data out of the websocket function I overwrote a text element on the page and simply made that element invisible. After that, just read the text element in order to get it into the rest of the code. However, there could be a better way of doing this so please let me knw if there is.
Also, there is one issue I ran into with this solution. When I originally tried this with normal formatting document.getElementById('some id').innerHTML = some data; it didn't work. But when with adding "window" to the beginning window.document.getElementById('some id').innerHTML = some data; it just worked.

Attempting to Import Module in Child Process (Javascript) and Failing

I'm currently running a heavy computation (i.e. generating a Monte Carlo tree), which is an expensive operation. I only have a few seconds to build as big of a tree as I can, so I am using subprocesses in Node.js in order to build multiple trees, and then aggregate their data together to make a more informed decision.
I understand that subprocesses do not share information/memory, and I need to use modules within these subprocesses that are located in a file, called "Epilog.js" on my machine.
When I run functions that are in epilog.js from the main file, it works just fine. But all of my functions that are in my worker threads return absolutely nothing.
I have tested to make sure that the parameters of the functions I am trying to use in "epilog.js" aren't empty, and they're not. The problem isn't in the parameter.
I have also tested to see what happens if I simply don't import, and instead of just outputting an undefined array, I get an error saying that there is no function called "findroles".
//My main thread.
var fs = require('fs');
eval(fs.readFileSync('epilog.js') + '');
var process = fork('./buildGraph.js');
process.send({library});
//My worker thread.
//buildGraph.js
var fs = require('fs');
eval(fs.readFileSync('epilog.js') + '');
// receive message from master process
process.on('message', async(message) => {
library = message["library"];
console.log(findroles(library));
// findroles(library) is a function that is defined in epilog.js,
//and this outputs an array of "roles" given a parameter,library.
// For some reason this function outputs [], rather than giving me
// all of the roles. If I run this exact line from my main thread,
// it doesn't give any errors and outputs the right array:
// e.g. ['red', 'white'].
});
I expect to get not the empty array, but [red, white], as I do if I were to run the same line in the main thread. Does anyone have an idea as to the inconsistency of the functions? I'm very new to node.js and this isn't a class focused too much on software engineering in JavaScript, so I'd appreciate if someone can dumb down what is going on, as this is all very new to me.
If your script does not find the function called findroles then there is a problem with the importing method. Using the eval function for importing is not the normal way of importing modules. Try something like this:
// buildGraph.js
const epilog = require("./epilog.js");
......
console.log(epilog.findroles(library));
then epilog.js
exports.findroles = function (library) {
// function content
}
You can find more info here:
https://www.w3schools.com/nodejs/nodejs_modules.asp
Base on the document and example here, everything seem correct but I think the problem come from this line:
var process = fork('./buildGraph.js');
you might override the original process.
try to change it to
const n = fork('./buildGraph.js');

why I can not use inline alert() in pug template if calling it from "if condition"?

I read in an article that I can use inline functions by defining them using - var = function(...){...}, but when I code:
- var tryit = function tryit(tasks) {alert('will not work')};
if tasks
#adiv #{tryit(tasks)}
I get this error message:
if supervisor tryit is not a function
I scanned all pug documentation (well there is no such thing there, sure!), please tell me how I can have this approach, so that I could further process my variable 'tasks' sent from server in client side.
My use case is that if I have a json array from server, process it further and add a tree structure of DOM elements. Then finally append it to the div(id='adiv'). I can't anyway figure out how to do this, because when I use document.createElement(...) I get a similar error like the above with alert(..). I tried by script. but then I can't call the method I declared in script. in pug template with #{myScriptedFunc(...)}.
Edit:
What surprises me more: if I change it to:
- var tryit = function() {console.log('silence!');};
if tasks
#adiv #{tryit()}
There will be no error message, but the output will be in server side (in command line window where I run the server), not in the browser, meaning that the line was executed in server side? But I expected to have it run in client side. The way to do such a post-processing in client side is still a mistry to me.
Your variable should hold the 'name' of the function, the function itself should be anonymous.
var tryit = function (tasks) {
alert('will work')
};
so var tryit = function tryit(tasks) becomes var tryit = function(tasks)
Alert can work, it doesnt look wonderful, but here it is:
if messages !== null
each message in messages
mixin alertMessage(message)
script.
debugger;
alert(message);
+alertMessage(message)
else
mixin alertMessage()
script.
debugger;
alert('Hey Look i work!');
+alertMessage()
Utlizing a mixin will allow you to call a function like block of code that you can put plain javascript in.
I suppose you could do the if check and just put the
script.
tag after that, but the
mixin
will allow you to iterate through an array or object you send in the route with
res.render('myPage', { anonymous object });

Server commands (or equivalent) in node.js

I have a server up and running in my digitaldomain droplet.
in my server code, I have a function called userCount(); which simply returns the number fo connected users.
I do not want to console.log the number of users on my server, each time someone is connected. This just creates a mess. Instead, I would like to be able to run this command whenever I need to see the "current user count".
How can I make my server in a way that, I will also be able to input commands to it (from the console) whenever it's needed?
What is the best and/or most optimal way of doing this?
How about exporting the relevant function and execute it whenever you feel like it?
droplet.js
...
function userCount() {
return 42;
}
...
module.exports = {
userCount: userCount
}
Create a wrapper file:
wrapper.js
var connected = require('./droplet.js');
console.log(connected.userCount());
Execute that file from the command line:
> node wrapper
If you do not want to create an additional file, use the node interface:
> node
console.log(require('./droplet.js').userCount());

WebdriverJS dump to terminal?

I am finding it very difficult to debug a test using WebDriverJs because I don't know how to see the value of a variable. For example, I am trying to access the window handle of a pop-up. I can test .toNotBe(null), but I would like to know the actual value. Every time I want to use it in the next logical step of driver.switchTo().window(handle) I get the error that NameOrHandle is not defined. That is probably the next question on SO; but for now I just want to know what node thinks "handle" is if not null but still not defined.
Is there a dump() command, or a helper library I can load into my spec with require that will allow me to dump an object's value to the terminal?
You should just be able to console.log() to dump your output to the terminal. For example:
driver.getAllWindowHandles().then(function(windows){
var originalWindow = windows[0];
var popupWindow = windows[1];
if (popupWindow) {
driver.switchTo().window(popupWindow);
driver.getTitle().then(function(popupTitle){
console.log("popupTitle is set to: ", popupTitle);
next();
});
}
});

Categories