How do I log anything to the console from meteor shell? - javascript

This GitHub issue documents that the console doesn't output anything to the meteor shell. Are there any workarounds? By default all console.log() statements will be output in the app's STDOUT (not in the shell).
Let's say we want to print certain items from a collection:
Meteor.users.find().forEach(function (user) {
if (...) console.log(user.emails[0].address;
});
That won't print anything. Here's what I've tried:
process.stdout.write() - doesn't print anything
Create a string buffer, append what we want to log to it, and evaluate it.
var output = '';
Meteor.users.find().forEach(function (user) {
if (...)
output += user.emails[0].address + "\n"
});
output;
This works but the \n is echoed literally, not as a line feed.
Evaluate the expression in the function. Predictably, this doesn't print anything.

One workaround I've used is to run the app in the background, then run the shell in the same window. i.e.
meteor run &
meteor shell
That way, everything that gets output in the app's console gets printed to your window. Admittedly, this won't help if you want to log only specific messages to your shell, but it helps if all you want is to avoid switching back and forth between multiple windows all the time.

Related

Unable to catch error when fetching data in async function

I'm using npm yahoo-finance to fetch stock data. When I input a stock symbol that doesn't exist, I would like to catch the error.
const yahooFinance = require('yahoo-finance');
async function stockData() {
try {
let data = await yahooFinance.historical({symbol: "SIJGAOWSFA", from: 2020-08-23, to: 2021-08-23});
} catch (error) {
console.error(error)
}
}
stockData();
However it doesn't appear to be a typical fetch error. It's not being caught at all. By that I mean, the error you see below was not logged to the console via the console.error(error). Rather something outside the scope of this file is logging the error. When the error occurs, nothing in catch is executed.
I plan on using this in a for loop, so would like to catch the error so I can avoid executing any following functions.
A collaborator says that:
Is this from an existing project that was working and stopped working, or a new project?
If the former - everything is still working fine on my side. (Very) occasionally there are issues at yahoo that get stuck in their cache, possibly relating to DNS too. I'd suggest to clear your DNS cache and also try querying different data to see if that works.
If the latter (new project), it could be the data you're querying. Try query different data and see if it works. Usually yahoo throws back a specific error if something wrong, but it could be this.
If neither of those approaches work, but you still need to catch this sort of error, given the source code, what it does is:
if (!crumb) {
console.warn('root.Api.main context.dispatcher.stores.CrumbStore.crumb ' +
'structure no longer exists, please open an issue.');
And then continues on as normal (without throwing), and eventually returns an empty array.
If you're sure the result should contain at least one item, you can check to see if it's empty, and enter into an error state if it is.
Otherwise, if you don't know whether the array should contain values or not, another option is to overwrite console.warn so that you can detect when that exact string is passed to it.
Another option would be to fork the library so that it (properly) throws an error when not found, instead of continuing on and returning an empty array, making an empty successful result indistinguishable from an errored empty result. Change the
if (!crumb) {
console.warn('root.Api.main context.dispatcher.stores.CrumbStore.crumb ' +
'structure no longer exists, please open an issue.');
to
if (!crumb) {
throw new Error('root.Api.main context.dispatcher.stores.CrumbStore.crumb ' +
'structure no longer exists, please open an issue.');
and then you'll be able to catch it in your call to .historical.

Capture console output of shellscript in nodejs

I have a nodejs function which calls a ShellScript xyz.sh. This shell script executes a jar file abc.jar and prints some output in the console. I am able to see some output lines from jar file execution in the console. But I am not able to capture them lets say to a variable. My requirement is to capture the error while executing logic present in jar file. Try catch is not helping here. Also, I cannot edit the java code and rebuild the jar file. But I would need to capture the output of jar file execution somehow in Nodejs and in case of errors while executing logic inside jar file, I need to take certain actions based on the error. So, can someone help me on how to capture the output of jar file in nodejs.
private async function_exec(abc: string) {
log.info('inside func_exec')
let result;
try
{
result = await asyncExec(
call xyz.sh; --> shell script gets called here
)
}
catch(error)
{
log.info('error is '+error);
}
log.info('result is '+result);
}
Output looks like below. I need to somehow capture messages like "Processing..",'Failed to Execute","Invalid system ID"
output:
runn_1 inside func_exec
runn_1 Processing..
runn_1 Failed to Execute
runn_1 Invalid system ID
runn_1 error is 1
runn_1 result is undefined

service.error() or service.setWarning() in Maximo automation javascript does not show popup on UI

I am trying to create an automation script (action launch point, trigger by a button on UI) for Maximo using javascript to do some data validation then show popup if there is invalid data.
I try to call service.setWarning() but the script still process instead of showing a warning message, if I do some UI interaction later, that warning message randomly display later.
Then I try the service.error() which should show an error message similar to the exception message in Maximo, the script does stop running but there is no popup message.
If I check systemError.log, I can see both the warning and error message displayed in the log?
So what is causing this and how can I make it behave correctly?
EDIT1: here is the script, I already setup the message in database configuration (messagegroup RFQ, messagekey 2VENDORS):
load("nashorn:mozilla_compat.js");
importPackage(Packages.psdi.security);
importPackage(Packages.psdi.mbo);
importPackage(Packages.psdi.server);
var mxServer = MXServer.getMXServer();
var userInfo = mxServer.getSystemUserInfo();
var rfqLineSet = mbo.getMboSet("RFQLINE");
var totalCost = 0;
var current_datetime = new Date();
var today = current_datetime.toISOString();
for(var currMbo=rfqLineSet.moveFirst(); currMbo!=null; currMbo=rfqLineSet.moveNext()) {
totalCost = totalCost + currMbo.getDouble("LINECOST");
}
if (totalCost < 50000) {
var rfqVendorSet = mbo.getMboSet("RFQVENDOR");
if (rfqVendorSet.count() > 2) {
service.error("RFQ","2VENDORS",null);
}
}
Maximo version 7.6.1
EDIT2: I tried the service.yncerror("RFQ","2VENDORS",null); which should display a yes/no error popup message but same issue, it only appears in the systemError.log
EDIT3: I did some tests and found out that if I write the code in Jython then the popup works but not in Javascript. How can this be?
UPDATE: I moved all my scripts to use python instead of javascript, seems that Maximo works best with automation script written in python.
Thanks.
"Warnings" in Maximo are some bits of data that just ride along with the MBO set. As a warning, they aren't supposed to stop execution, just let you know of something important, but they won't even do that on their own. You need to do something at some point to fetch the warnings from the set and display them. If you don't, Maximo will on its own for certain actions (usually for those actions that would include a warning Maximo itself added), but that probably isn't when you actually want it to be displayed. I have seen many people mix this up and not understand what these warnings are or how they actually work.
"Errors" are meant to be logic stopping messages. Something went wrong and the user needs to know about it before more logic runs. This sounds more like your use case. Errors are still meant to be a message to the user though, so you have to supply a message for the error method. You can't just put any string you want as your message in there though (well, you shouldn't) as that doesn't allow Maximo to translate the message or fill in message variables. It also means you have to change code whenever you want to change the message, instead of simply changing a configuration live. Instead you need to go to Database Configuration and add a new message in there. When you do that, you will create a message group and message key value for your message. Now when you call the error method, you will pass in that error group and error key as parameters. Maximo will take that, look it up in the message table and then display the message associated with that group and key for your configured language. It can also replace some special message variables at this time too, but that's a lesson for another time.
For example, you might go to Database Configuration and open the dialog for the messages and add a message of "The value you entered in the 'count' field is not a number. Please enter a number before continuing." and give it a message group of "MyCustomGrp" and a key of "NotANumber". Then in your code when you want to stop the code and display that message, you would call service.error("MyCustomGrp", "NotANumber").
The other potential problem you could be having is that you do need to be running the code that throws the error in some way attached to the interactive user session. Generally, that's a given, but there are some things you could be doing that would cause your code to run separate from that interactive user session. If you are seeing your error message in the logs, then you have set that part up correctly and it likely means your code is not part of the interactive user session. This is where knowing the rest of your code is very important.

JS node issue with for and foreach loops

This is really puzzling me, until 4 days ago everything was working fine and no problems were occurring, but then an issue started when two of my cron daemon jobs stopped working.
I thought nothing of it and decided to rebuild the code and improve it a little as I have gained more insight since the files were coded the first time around.
Here is the problem:
this one works as expected on local machine
Object.keys(res).forEach(function(key) {
const row = res[key];
client.channels.get(row.forchannel).send({ embed });
console.log(row.forchannel);
});
and so does this one:
res.forEach(function(row) {
client.channels.get(row.forchannel).send({ embed });
console.log(row.forchannel);
});
and also this one:
for (let i = 0; i < res.length; i++) {
console.log(res[i]);
client.channels.get(res[i].forchannel).send({ embed });
}
The issue I have is that non of them work when I upload to live server, the results from a MySQL query are there when I console log out of the loop on live, console logging inside the loop on live shows nothing except for the last block of code I posted and this returns one result.
Local machine is windows running Node v11.6 and live is Ubuntu running a v11.12 of node.
So to summary:
On the live server those loops above are not working, I can return arrays when console logging data outside of the loops but on only the last one does any data show when console logging inside the loop.
On local machine everything works as expected, In both cases error catching reports null so there are no errors.
res.map((result) => {
client.channels.get(result.forchannel).send({ embed });
});
It might help you.
I discovered what the problem was, although my bot has both a subscribe and an unsubscribe option my code does not cater for the obvious: A discord server Admin deleting a channel, this then leaves a row in the database that when fed into the loop comes back false as the channel no longer exists and stops the auto-posting.
Working code first checks if the channel does actually exist before processing through the array.
res.map((result) => {
if (client.channels.has(result.forchannel)) {
client.channels.get(result.forchannel).send({ embed });
}
});
client.channels.has checks that the channel exists and because its in an if statement will only proceed to post on channels that return true.

Can't iterate over array in certain pages

I have this simple array:
var a = new Array();
a.push(o);
When running this code:
a.forEach(function(o){console.log(o)});
In a blank page - I can see the object being logged to the console.
The thing is - I have this code running in a another page and
The foreach loop does not log anything, even though I can see the object in a[0].
I suspect this may has to do with the Prototype JS lib that this page utilizes- though I wasn't able to prove it.
Does that sound familiar?
Thanks.
The prototype replaces console log messages, use this code to see the actual console log:
delete console.log
After this console messages will appear.

Categories

Resources