Node.js function output to variable - javascript

i have a grep function that i am using to seperate some data out.
I ran into an issue, instead of outputting the data to the console, i need it to store it to a variable.
for example, here is my actual function.
function funGrep(cmd,callback,search,args){
exec(cmd,function(err,stdout){
if(!stdout)
return;
var lines = stdout.toString().split(EOL);
var re = new RegExp(search,args);
for(var line in lines){
var results = lines[line].match(re);
if(results){
for(var i = 0; i < results.length; i++){
callback(results[i]);
}
}
}
});
}
and here is my actual calling of the function into play.
funGrep("ping -n 3 google.com",console.log,"time=[0-9\.]+ ?ms");
instead of logging the output to the console, how can i just assign it to a variable like output.
thank you!

All you should have to do is create your own callback function that does whatever you need it to do with your data/results. It would look something like this:
function theCallback (data) {
... do whatever you want with your data ...
}
And then instead of console.log, you would pass in this function as an argument.
funGrep("ping -n 3 google.com",theCallback,"time=[0-9\.]+ ?ms");

You could you the callback to append the data to a variable, and modify the callback to notify the handler when the function has finished:
function funGrep(cmd,callback,search,args){
exec(cmd,function(err,stdout){
if(err){
console.log(err);
return;
}
if(!stdout)
return;
var lines = stdout.toString().split(EOL);
var re = new RegExp(search,args);
for(var line in lines){
var results = lines[line].match(re);
if(results){
for(var i = 0; i < results.length; i++){
callback(results[i],false);
}
}
}
callback(null,true); //finsished
});
}
var myData = [];
funGrep("ping -n 3 google.com",function(result,finished){if(!finished) myData.push(result); else goOn();},"time=[0-9\.]+ ms");
function goOn(){
//funGrep finished
console.log("Result: " + myData);
}

Related

Retrieving a variable from within a function

I am attempting to pull information from the League of Legends API.
To simplify what I am doing, I am attempting to pull information about a user and their previous matches. The problem that I run into is that when I parse a JSON request, it returns a champion ID rather than their name (Ex: 412 rather than "Thresh").
The only solution I can see for this would be to make another JSON request and parse that data for the champion name. Currently what I have looks like this.
$.getJSON(championMasteryPHP, function (json) {
for (var i = 0; i < 20; i++) {
var champID = json[i].championId;
var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;
$.getJSON(championInfo, function (json2) {
var champName = json2.name;
});
$('#champ').append("<li>"+champID+" - "+champName+"</li>")
}
});
I'm unable to access the champName variable due to it being nested within the second JSON function.
Is there a better way to do this?
$.getJSON(championMasteryPHP, function (json) {
for (var i = 0; i < 20; i++) {
var champID = json[i].championId;
var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;
$.getJSON(championInfo, function (json2) {
var champName = json2.name;
$('#champ').append("<li>"+champID+" - "+champName+"</li>")
});
}
});
Just put it inside the second json request since you need to wait till that request is done anyway.
You should put the append statement in the callback because getJSON is an asynchronous method (does mean the Request is running in the background, and calls your function back when it got a response), so you should wait for the response first then you can append it to #champ :
$.getJSON(championMasteryPHP, function (json) {
for (var i = 0; i < 20; i++) {
var champID = json[i].championId;
var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;
$.getJSON(championInfo, function (json2) {
var champName = json.name;
$('#champ').append("<li>"+champID+" - "+champName+"</li>")
});
}
});
Hope this helps.

Nested for loop with inner functions

In javascript For loop it's works fast and inner functions are not called. I am trying to store images in database using cordova. In my code for loop works fast and finished but I didn't get any base64 images.
for(var i = 0; i < pages.length; i++)
{
var cat_img = res.Catalogue[0].Catalogue_img;
var catalogue_image_id = cat_img[i].catalogue_image_id;
var catalogue_image = cat_img[i].catalogue_image;
getBase64FromImage(catalogue_image,function (baseData64) {
console.log("baseData64===="+baseData64);
insertPageData (catalogue_image, catalogue_image_id);
},function (error) {
console.log("error====="+error);
});
}
Thanks in advance!!
Your callback "function (baseData64)" will be executed only when the image is downloaded and converted to base64. At that point, the value of "calalogue_image" and "catalogue_image_id" will contain the value of the last element in the loop - with "i = pages.length"
That is, your for loop finishes probably before even the first image is downloaded.
Actually I think the valid behaviour is that you should see only the last image, with "i = pages.length" in the database.
Try this
var processImage = function (cImg,cImgId){
var catalogueImage = cImg;
var catalogueImageId = cImgId;
return function (baseData64) {
console.log("baseData64===="+baseData64);
insertPageData (catalogueImage, catalogueImageId);
}
}
for(var i = 0; i < pages.length; i++)
{
var cat_img = res.Catalogue[0].Catalogue_img;
var catalogue_image_id = cat_img[i].catalogue_image_id;
var catalogue_image = cat_img[i].catalogue_image;
getBase64FromImage(catalogue_image,
processImage(catalogue_image, catalogue_image_id) ,
function (error) {
console.log("error====="+error);
}
);
}

javascript "don't make function in a loop"

How can I refractor my code to get rid of this error from JSLinter?
I tried moving the entire function out to a var but the code wasn't able to run after that.
for (i = 0; i < timeDifference; i++) {
timestamp ++;
console.log(timestamp);
energyDatum.find({timestamp: timestamp}).toArray(function(err, result) {
var data = {};
result.forEach(function(element) {
data[element.deviceId] = element;
});
var roomRawData = [];
mappings.forEach(function(room) {
var hash = {};
hash.floor = room.floor;
hash.name = room.name;
hash.room_type = room.room_type;
hash.energy_ac = sumApplianceEnergy('energy_ac', room, data);
hash.energy_light = sumApplianceEnergy('energy_light', room, data);
hash.energy_socket_1 = sumApplianceEnergy('energy_socket_1', room, data);
hash.energy_socket_2 = sumApplianceEnergy('energy_socket_2', room, data);
hash.energy_socket_3 = sumApplianceEnergy('energy_socket_3', room, data);
hash.energy_total = hash.energy_ac + hash.energy_light + hash.energy_socket_1 + hash.energy_socket_2 + hash.energy_socket_3;
hash.timestamp = timestamp;
roomRawData.push(hash);
});
roomRaw.insert(roomRawData, {w:1}, function(err, result) { console.log('done'); });
});
lastTimestamp.update({_id: timestampId}, {timestamp: timestamp});
}
JSLinter shows this message because your code has potential errors.
Take a look at this line:
energyDatum.find({timestamp: timestamp}).toArray(...);
This method is async, right? It means that the callback of toArray method
is called after the for loop finishes its iterations, and therefore timestamp
variable (when you use it inside this callback) doesn't have a value of current iteration,
but instead it has value incremented for timeDifference times.
To solve this problem you could move this callback to another function:
var getIterationFunc = function(timestamp) {
return function(err, result) {
var data = {};
// rest of function ...
}
}
and then use it:
energyDatum.find({timestamp: timestamp}).toArray(getIterationFunc(timestamp));
I believe this error should be fixed now. Hope this helps.
P.S. sorry for my English

Can't read values that are outside of function

I am learning JavaScript and AngularJS. I want to use the values that are outside of function, but I don't know how to access them.
Here is my code (AngularJS Controller):
var init = function() {
$http.get('getSomeValues').then(function (res) {
var returnArray = res.data; // Result is array
for(var i=0; i < returnArray.length; i++) { // Loop through the array
console.log("THIS WORKS FINE: ", returnArray[i].value); // It works
$http.get('getOtherValues/' + returnArray[i].value).then(function (res) {
console.log("WHAT'S IN IT: ", returnArray[i].value); // Shows 'undefined' error
});
}
});
};
init();
So basically I want to access the array returnArray, but I can't. Is there any good way to access the values? I assume that '.then(function ..' causes error..
You'll need to use a IIFE:
Replace:
for(var i=0; i < returnArray.length; i++) { // Loop through the array
$http.get('getOtherValues/' + returnArray[i].value).then(function (res) {
console.log("WHAT'S IN IT: ", returnArray[i].value); // Shows 'undefined' error
});
}
With:
for(var i=0; i < returnArray.length; i++) { // Loop through the array
(function(data){
$http.get('getOtherValues/' + data.value).then(function (res) {
console.log("WHAT'S IN IT: ", data.value); // Shows 'undefined' error
});
}(returnArray[i]))
}
This ensures that, for the current iteration of the for loop, the data variable will be set to the current raturnArray item.

Simpy cannot iterate over javascript object?

I have scoured the other question/answer for this and implemented everything and I still cannot access the values of the object. Here's the code I am using:
function apply_voucher(voucher) {
var dates = $.parseJSON($("[name='dates']").val());
var voucher_yes_no = new Array();
var voucher_reduction = new Array();
if(voucher.length > 0)
{
$.each(dates, function(room_id, these_dates) {
$.post('/multiroom/check_voucher/'+voucher+'/'+room_id, function(result) {
if(result.result == 'ok') {
voucher_yes_no.push('yes');
voucher_reduction.push(result.voucher_reduction);
} else {
voucher_yes_no.push('no');
}
}, 'json');
});
// check if there are any yes's in the array
if('yes' in voucher_yes_no) {
console.log("no yes's");
} else {
console.log(voucher_reduction);
console.log(typeof voucher_reduction);
for (var prop in voucher_reduction) {
console.log(prop);
console.log(voucher_reduction[prop]);
if (voucher_reduction.hasOwnProperty(prop)) {
console.log("prop: " + prop + " value: " + voucher_reduction[prop]);
}
}
}
}
}
Apologies for the constant console logging - I'm just trying to track everything to make sure it's all doing what it should. The console output I get from this is below:
...which shows the object containing one value, "1.01" and my console.log of the typeof it to make sure it is actually an object (as I thought I was going mad at one point). After this there is nothing from inside the for-in loop. I have tried jquery's $.each() also to no avail. I can't understand why nothing I'm trying is working!
It does not work because the Ajax call is asynchronous!
You are reading the values BEFORE it is populated!
Move the code in and watch it magically start working since it will run after you actually populate the Array!
function apply_voucher(voucher) {
var room_id = "169";
var dates = $.parseJSON($("[name='dates']").val());
var voucher_reduction = new Array();
$.post('/multiroom/check_voucher/'+voucher+'/'+room_id, function(result) {
if(result.result == 'ok') {
voucher_reduction.push(result.voucher_reduction);
}
console.log(voucher_reduction);
console.log(typeof voucher_reduction);
for (var prop in voucher_reduction) {
console.log(prop);
console.log(voucher_reduction[prop]);
if (voucher_reduction.hasOwnProperty(prop)) {
console.log("prop: " + prop + " value: " + voucher_reduction[prop]);
}
}
}, 'json');
}
From what it looks like, you plan on making that Ajax call in a loop. For this you need to wait for all of the requests to be done. You need to use when() and then(). It is answered in another question: https://stackoverflow.com/a/9865124/14104
Just to say for future viewers that changing the way I did this to use proper deferred objects and promises, which blew my head up for a while, but I got there! Thanks for all the help, particularly #epascarello for pointing me in the right direction :) As soon as I started doing it this way the arrays began behaving like arrays again as well, hooray!
Here's the final code:
function apply_voucher(voucher) {
var booking_id = $("[name='booking_id']").val();
var dates = $.parseJSON($("[name='dates']").val());
if(voucher.length > 0) {
var data = []; // the ids coming back from serviceA
var deferredA = blah(data, voucher, dates); // has to add the ids to data
deferredA.done(function() { // if blah successful...
var voucher_yes_no = data[0];
var voucher_reduction = data[1];
if(voucher_yes_no.indexOf("yes") !== -1)
{
console.log("at least one yes!");
// change value of voucher_reduction field
var reduction_total = 0;
for(var i = 0; i < voucher_reduction.length; i++) {
reduction_total += voucher_reduction[i];
}
console.log(reduction_total);
}
else
{
console.log("there are no yes's");
}
});
}
}
function blah(data, voucher, dates) {
var dfd = $.Deferred();
var voucher_yes_no = new Array();
var voucher_reduction = new Array();
var cycles = 0;
var dates_length = 0;
for(var prop in dates) {
++dates_length;
}
$.each(dates, function(room_id, these_dates) {
$.post('/multiroom/check_voucher/'+voucher+'/'+room_id, function(result) {
if(result.result == 'ok') {
voucher_reduction.push(result.voucher_reduction);
voucher_yes_no.push('yes');
} else {
voucher_yes_no.push('no');
}
++cycles;
if(cycles == dates_length) {
data.push(voucher_yes_no);
data.push(voucher_reduction);
dfd.resolve();
}
}, 'json');
});
return dfd.promise();
}
Can you show how voucher_reduction is defined?
I am wondering where the second line of the debug output comes from, the one starting with '0'.
in this line:
console.log(vouncher_reduction[prop]);
^
The name of the variable is wrong (then) and probably that is breaking your code.
I think there are no problem with your loop.
But perhaps with your object.
Are you sure what properties has enumerable ?
Try to execute this to check :
Object.getOwnPropertyDescriptor(voucher_reduction,'0');
If it return undefined, the property was not exist.

Categories