Boolean fileContainsString not working - javascript

I have a function that returns a boolean of whether or not a file contains a string. I know the checkFileForString function runs and properly assigns the boolean value as true but the code within the if statement at the bottom does not run.
var checkFileForString = function (fileName) {
var yesStringFound = false;
fs.readFile(fileName, function (err, data) {
if (err) throw err;
if(data.indexOf('yes') >= 0){
yesStringFound = true;
}
console.log('YES STRING FOUND: ' + yesStringFound);
});
return yesStringFound;
};
console.log("instanceCount >= 4...");
if (checkFileForString(quadrantFile0) == true) { //todo: confirm and fix
console.log("runs...");
assignToQuadrant(0, maxInstances);
quadrantOccupied = 0;
setQuadrantAsUnavailable(quadrantOccupied);
}

Solution I got with help from #nnnnnn:
var checkFileForString = function (fileName) {
var yesStringFound = false;
var jsonFile = fs.readFileSync(fileName);
if(jsonFile.indexOf('yes') >= 0)
yesStringFound = true;
return yesStringFound;
};

Related

Value of Variable within Function NOT Changing when using If Statement in HTTP GET Request

I have a variable called
let idStatus = '';
I need my getValues function to return true and am using this variable to determine whether it returns true or false.
function getValues(){
let idStatus = '';
let getValuesUrl = 'https://something.something.com/v1.0/something/1?apiKey=1234abcdefghijklmnop';
const getValuesRequest = new XMLHttpRequest();
getValuesRequest.responseType = 'json';
getValuesRequest.open('GET', getOptionValuesUrl);
getValuesRequest.send();
getValuesRequest.onreadystatechange = function () {
const response = getValuesRequest.response;
if (response) {
if (getValuesRequest.status == 200) {
console.log('Success');
if(validateIds(response)){
console.log('ID is Valid');
idStatus = true;
}
else {
console.log('ID is NOT Valid');
idStatus = false;
}
}
}
console.log(idStatus);
return idStatus;
}
function validateIds(obj) {
const data = obj['data'];
console.log(data);
let validId = '';
for (let i = 0; i < data.length; i++) {
if (data[i].id == 1) {
validId = true;
}
else {
validId = false;
}
}
console.log(validId);
return validId;
}
Valid IDs runs the way it should and getValues console.logs the appropriate responses when it is true or false, yet idStatus always returns null.
Here I've made a simpler version of your code. I used axios instead of XMLHttpRequest as it's simpler to use.
const axios = require("axios");
async function getValues(link) {
const response = await axios.get(link);
if (!response.statusCode == 200) return false;
if (response.data.some(elm => elm.id != 1)) return false;
return true;
}
// if the status isn't 200, return false;
if (!response.statusCode == 200) return false;
// if one id isn't 1, return false;
if (response.data.some(elm => elm.id != 1)) return false;
If you want more details on Array.some(), here's a link Array.Some()

CosmosDb Stored procedure There Is An error In My Javascript

There is an error in my Javascript but I just can't understand why. In the code below when the function
function replaceDoc(document,callback)
is called the document is null. I have checked that there are documents in the feed from
function tryQuery(callback) {...
and there is some kind of error. The procedure runs fine and response body shows this. Where is my mistake please?
function bulkChangeJobNumber(docs) {
var collection = getContext().getCollection();
var collectionLink = collection.getSelfLink();
var response = getContext().getResponse();
var responseBody = {
docsRetrieved: 0,
msg:'',
msg2:''
}
var docs;
var count = 0;
//get the docs
tryQuery(callback);
function tryQuery(callback) {
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
"SELECT * FROM c WHERE c.ty = 'job' AND NOT IS_DEFINED(c.jobNumber)", function (err, feed, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else take 1st element from feed
docs = feed;
responseBody.docsRetrieved = docs.length;
responseBody.msg = options;
responseBody.msg2 = docs[0];
if (feed.length == 0) {
response.setBody("No Docs");
}
else{
replaceDoc(docs[count],callback);
}
});
if (!isAccepted) {
response.setBody("The query was not accepted!");
return;
}
}
function replaceDoc(document,callback){
if(document == null){
responseBody.msg = "document is null";
response.setBody(responseBody);
return;
}
document.jobNumber = document.jobId;
var accept = collection.replaceDocument(document._self,document, callback);
if(!accept){
response.setBody(`Processed: ${count} docs`);
}
}
function callback(err,doc,options){
if (err) throw err;
count++;
if(count > docs.length){
response.setBody(`processed all ${count} docs`)
}else{
replaceDoc(docs[count],callback);
}
}
}

How to solve incorrect return value of javascript+firebase function due to order of operation is different when retrieving data?

I am currently implementing a javascript function to judge if user id and name matches or not.
function name_match(user_id, user_realname) {
var dbref = firebase.database().ref();
var namesref = dbref.child("names");
namesref.on("value", function(snapshot) {
snapshot.forEach(i => {
if(i.key == user_id && i.child("realname").val() == user_realname) {
return true;
}
});
});
return false;
}
However, regardless of input, it will initially return false. I think this is because it will go to "return false" while firebase data is loading.
So, even if eventually returns true, since the first-time return value is false, it causes a problem in like this (in another function).
function name_match2() {
var user_id = document.getElementById("user-id").value;
var user_realname = document.getElementById("user-realname").value;
if(!name_match(user_id, user_realname)) return -1;
return 0;
}
And it will return -1.
Can you explain how to solve this problem?
As explained by Daniel in the comment, outer function never returns true. The async solutions could be these :)
function name_match(user_id, user_realname) {
return new Promise(function (resolve, reject) {
var dbref = firebase.database().ref();
var namesref = dbref.child("names");
namesref.on("value", function(snapshot) {
var matched = false;
snapshot.forEach(i => {
if(i.key == user_id && i.child("realname").val() == user_realname) {
matched = true;
}
});
if (matched) {
resolve()
} else {
reject()
}
});
});
}
On the other side of calling function
name_match('userId', 'userName').then(function(){
//matched
}, function(){
//unmatched
});
Other way would be to use Callbacks:
function name_match(user_id, user_realname, cb) {
var dbref = firebase.database().ref();
var namesref = dbref.child("names");
namesref.on("value", function(snapshot) {
var matched = false;
snapshot.forEach(i => {
if(i.key == user_id && i.child("realname").val() == user_realname) {
matched = true;
}
});
cb(matched);
});
}
In this case:
name_match('userId', 'userName', function(matched) {
console.log(matched);
})
Here is a small adaptation of Suryapratap solution, using the once() method, which
"Listens for exactly one event of the specified event type, and then stops listening.", and
Returns a Promise
... instead of using the on() method which sets a listener.
function name_match(user_id, user_realname) {
var dbref = firebase.database().ref();
var namesref = dbref.child("names");
return namesref.once('value').then(function(snapshot) {
var matched = false;
snapshot.forEach(i => {
if(i.key == user_id && i.child("realname").val() == user_realname) {
matched = true;
}
});
return matched;
});
}

Unable to return result from promise

I am trying to read some data from 2 different tables and parse a CSV file before rendering an ejs file.
I can get the data from both tables and from the CSV file but I seem to be unable to return the result.
Pretty sure this is a problem with the way I handle async execution but I fail to see what I am doing wrong.
I've spent the last 2 days reading about this (including the threads around here) and browsing but somehow the answer still escapes me.
First file - usercms.js
app.get('/userscms', function(req, res)
{
existingUsers.getExistingUsers()
.then(function(appUsers)
{
//global users array
//I can display these in my ejs file
globalAppUsers = appUsers;
})
.then(existingUsersAttributesQlik.getExistingUsersAttributesQlik())
.then(function(usersQlikAttributes)
{
//global user attributes array
//undefined data
globalUsersQlikAttributes = usersQlikAttributes;
})
.then(existingSuppliers.parseSuppliersCSV())
.then(function(supplierData)
{
//the result I am expecting
//this prints undefined
console.log(supplierData);
}).then(function()
{
res.render('userscms.ejs',
{
users: globalAppUsers,
attributes: globalUsersQlikAttributes
});
});
});
Second function - getxistingUsers.js (identical to the getExistingUsersAttributesQlik, except for the query)
var userData = [];
var appUsers = [];
(function (exports)
{
exports.getExistingUsers = function ()
{
return promisemysql.createConnection(dbconfig.development).then(function(conn)
{
var result = conn.query("SELECT id, username, firstName, lastName, email, phone, lastLogin, isAdmin, isValid, isPhoneValid, accountCreationDateTime FROM Users");
conn.end();
return result;
}).then(function(rows)
{
return rows;
}).then(function(rows)
{
if (rows.length)
{
userData = [];
appUsers = [];
rows.forEach(function (elem)
{
userData.push(_.toArray(elem));
});
for (i = 0; i < userData.length; i++)
{
var appUser = new appUserModel.AppUser(
userData[i][0],
userData[i][1],
userData[i][2],
userData[i][3],
userData[i][4],
userData[i][5],
userData[i][6],
userData[i][7],
userData[i][8],
userData[i][9],
userData[i][10]);
appUsers.push(_.toArray(appUser));
}
return appUsers;
}
else
{
console.log("NOPE");
return null;
}
}).then(function(appUsers)
{
console.log(appUsers);
return appUsers;
});
};
})(typeof exports === 'undefined' ? this['getExistingUsers'] = {} : exports);
Third file - parseSuppliersCSV.js
var supplierData = [];
var suppliersData = [];
var csvCount = 0;
(function (exports)
{
exports.parseSuppliersCSV = function ()
{
return new Promise(function(resolve, reject)
{
var fileStream = fs.createReadStream("myCSV.csv");
var parser = fastCsv();
csvCount = 0;
supplierData = [];
suppliersData = [];
fileStream
.on("readable", function ()
{
var data;
while ((data = fileStream.read()) !== null)
{
parser.write(data);
}
})
.on("end", function ()
{
parser.end();
});
parser
.on("readable", function ()
{
var data;
while ((data = parser.read()) !== null)
{
if(csvCount >= 1)
{
csvCount++;
var arrayOfStrings = data[0].split(';');
var supplier = new supplierModel.Supplier(arrayOfStrings[0],arrayOfStrings[1]);
suppliersData.push(_.toArray(supplier));
}
else
{
csvCount++;
}
}
})
.on("end", function ()
{
console.log("done");
//all OK here
console.log(suppliersData);
//this doesn't seem to return anything
return suppliersData;
});
});
};
})(typeof exports === 'undefined' ? this['parseSuppliersCSV'] = {} : exports);
Any ideas what I am doing wrong? Am I approaching this the wrong way?
I'll take a guess here and assume the promise you created should resolve to something...instead of returning a value.
.on("end", function ()
{
console.log("done");
//all OK here
console.log(suppliersData);
//this doesn't seem to return anything
return resolve(suppliersData);
});

Javascript Returning from within a nested function

I'm trying to return the output of the randomizer function within a route... I keep getting 'undefined' - but no idea what I'm doing wrong...
var randomizer = function() {
// A load of stuff happens here.. and functions that are needed by the pullOut function (I've removed for brevity)
var pullOut = function(pick) {
if (playerList.length !== pick) {
var random_item = getRandomItem(list, weight);
if (playerList.indexOf(random_item) == -1) { // doesn't exist. So add to array.
playerList.push(random_item);
}
pullOut(pick);
} else {
console.log(playerList)
return playerList;
}
}
return pullOut(pick);
}
router.route('/ordercreated')
.post(function(req, res) {
var orderedItems = req.body.line_items;
// I foreach through all the items - calling the randomizer function on each one...
_.forEach(orderedItems, function(n) {
Pack.findOne({
'product_id': n.variant_id
}, function(err, pack) {
if (err) {
return res.send(err);
}
if (pack) {
var list = [];
var weight = [];
_.forEach(pack.playerData, function(n) {
list.push(n.name);
weight.push(parseInt(n.chance));
});
console.log('randomizing', randomizer(pack.title, list, weight, n.qty, pack.pick));
}
});
});
res.sendStatus(200);
})
Your "pullOut" function calls itself, but it throws away the result of that call.
var randomizer = function() {
// A load of stuff happens here.. and functions that are needed by the
// pullOut function (I've removed for brevity)
var pullOut = function(pick) {
if (playerList.length !== pick) {
var random_item = getRandomItem(list, weight);
if (playerList.indexOf(random_item) == -1) { // doesn't exist. So add to array.
playerList.push(random_item);
}
return pullOut(pick); // <--- add return
} else {
console.log(playerList)
return playerList;
}
}
return pullOut(pick);
}
Without that return, when the function took that path through the main if statement it would return undefined.

Categories