Capture messages in from python-shell in an array - javascript

I am new to Javascript but am attempting to build an Electron app as a gui to a python script.
I am using python-shell to call my Python script and can successfully do this and printing the output in the console. However I would like to capture multiple Python print statements in a Javascript array.
Following the python-shell docs I can access each Python print statement via the message event.
var res = [];
var ligation = PythonShell.run("ligation.py", options, function (err, results) {
if (err) throw err;
// console.log('results: %j', results);
});
ligation.on('message', function(message) {
// console.log(message)
res.push(message)
})
console.log(res)
However when I try to assign the ouput of these events to an array it works but I cannot access the values as the console looks like this:
where the 8 numbers are my output. When I try to access a single value (e.g. console.log(res[0])) I get it reported that it is undefined.
I gather that the little blue i means that the values are just evaluated and figure this may have something to do with it but I do not know what.
I figure there must be something straightforward I am missing. Any help is appreciated.

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.

Error in res.render, function not defined

I have developed an application using express js. I am trying to fetch data from my mongo collection, below is the javascript file and on fetching the data i am passing the data to a jade file through res.render function. One point to note is that i have several functions like the one below and all are synchronous. Still my console says "TypeError: undefined is not a function"
It is showing error on res.render line.
Any help is deeply appreciated. If someone needs more info about the question, please let me know.
exports.getData_app = function(req,res){
var nine = function(callback){
wpt_results.find({$and: [{"Environment":"app"},{"Module":"paid"},{browser_name:'Internet Explorer'}]},{},function(e,docs){
console.log('here is the doc fetched from the collection app');
// console.log(docs);
len = docs.length;
console.log('here is the length of the docs fetched in app');
console.log(len);
console.log("we are in the new one app javascript file");
console.log("here is the much awaited result"+req.params.id);
for(i=0;i<docs.length;i++){
dates_apppaid_ie.push(docs[i].Date);
ttfbs_apppaid_ie.push(docs[i].TTFB);
lt_apppaid_ie.push(docs[i].loadTime);
url.push(docs[i].Url);
}
for(i=0;i<len;i+=2){
pre_final_str_apppaid_ie.push(dates_apppaid_ie[i]+","+ttfbs_apppaid_ie[i]+","+ttfbs_apppaid_ie[i+1]+","+lt_apppaid_ie[i]+","+lt_apppaid_ie[i+1]+"\\n");
}
console.log(pre_final_str_apppaid_ie);
console.log(pre_final_str_app.length);
for(i=0;i<pre_final_str_apppaid_ie.length;i+=2){
final_str_apppaid_ie += pre_final_str_apppaid_ie[i].concat(pre_final_str_apppaid_ie[i+1]);
}
console.log('app ---->>>>>'+final_str_apppaid_ie);
res.render('index1.jade',{final_str_appreporting: final_str_appreporting,final_str_apppaid: final_str_apppaid, final_str_app: final_str_app, final_str_app_firefox:final_str_app_firefox,final_str_appreporting_firefox:final_str_appreporting_firefox,final_str_apppaid_firefox:final_str_apppaid_firefox,final_str_app_ie:final_str_app_ie,final_str_appreporting_ie:final_str_appreporting_ie,final_str_apppaid_ie:final_str_apppaid_ie});
});
callback(null,nine);
}
Got it. I was getting this error because i had defined a string with the name "res". On changing it to something else, res.render is working fine.

NodeJS - Storing command line output as a var and returning it to client via res.send()

I am currently working on the back end of an application, using NodeJS. As part of my code, I read the first line of a file and send that to a client using res.json. My code looks like this
var hr = 'head -n 1 ../' + req.file.path + '_hr.txt';
exec(hr, function (error, stdout, stderr) {
console.log(hr);
console.log(stdout);
console.log(stderr);
res.json({
"heartrate": stdout
});
})
When I execute this however, I get
{"heartrate" : ""}
even though on the console of the back end I see a value for stdout.
I have looked at other related questions but the information I've got has been in bits and pieces. I realise the object produced by stdout is not a string. I tried the toString() method on it but that didn't work.
I also put an if(stdout) around the res.json since exec is ansynchronous and may stdout may not have been written to at the point when I call console.log(stdout), but that also did not work.
I also tried using spawn instead of exec to no avail, although I may have used it wrongly. I'm sure the solution to my problem is very simple, but I have not been able to find it. Any help will be appreciated!
So it turns out I was logging the wrong stdout, logged the right one and got the answer I wanted

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

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.

How do I read a file in Node.js?

In Node.js, I want to read a file, and then console.log() each line of the file separated by \n. How can I do that?
Try this:
var fs=require('fs');
fs.readFile('/path/to/file','utf8', function (err, data) {
if (err) throw err;
var arr=data.split('\n');
arr.forEach(function(v){
console.log(v);
});
});
Try reading the fs module documentation.
Please refer to the File System API's in node.js, there is also few similar questions on SO, there is one of them
There are many ways to read a file in Node. You can learn about all of them in the Node documentation about the File System module, fs.
In your case, let's assume that you want to read a simple text file, countries.txt that looks like this;
Uruguay
Chile
Argentina
New Zealand
First you have to require() the fs module at the top of your JavaScript file, like this;
var fs = require('fs');
Then to read your file with it, you can use the fs.readFile() method, like this;
fs.readFile('countries.txt','utf8', function (err, data) {});
Now, inside the {}, you can interact with the results of the readFile method. If there was an error, the results will be stored in the err variable, otherwise, the results will be stored in the data variable. You can log the data variable here to see what you're working with;
fs.readFile('countries.txt','utf8', function (err, data) {
console.log(data);
});
If you did this right, you should get the exact contents of the text file in your terminal;
Uruguay
Chile
Argentina
New Zealand
I think that's what you want. Your input was separated by newlines (\n), and the output will be as well since readFile doesn't change the contents of the file. If you want, you can make changes to the file before logging the results;
fs.readFile('calendar.txt','utf8', function (err, data) {
// Split each line of the file into an array
var lines=data.split('\n');
// Log each line separately, including a newline
lines.forEach(function(line){
console.log(line, '\n');
});
});
That will add an extra newline between each line;
Uruguay
Chile
Argentina
New Zealand
You should also account for any possible errors that happen while reading the file by adding if (err) throw err on the line right before you first access data. You can put all of that code together in a script called read.js like this;
var fs = require('fs');
fs.readFile('calendar.txt','utf8', function (err, data) {
if (err) throw err;
// Split each line of the file into an array
var lines=data.split('\n');
// Log each line separately, including a newline
lines.forEach(function(line){
console.log(line, '\n');
});
});
You can then run that script in your Terminal. Navigate to the directory that contains both countries.txt and read.js, and then type node read.js and hit enter. You should see the results logged out on the screen. Congratulations! You've read a file with Node!

Categories

Resources