Global Dictionary/Scope Issue - javascript

I've defined a global dictionary, and I want to add to it within a MySQL connection block. Problem is, once outside of that block, the dictionary appears empty. This feels like a basic scope problem, but it seems odd that things added to the dictionary won't stay put, no?
Code:
var express = require("express");
var http = require("http");
var mysql = require("mysql");
objects = {};
getBiz = function() {
var connection = mysql.createConnection({
host:"localhost",
user:"APIUser",
password:"password"
});
connection.query("USE biz");
var bizQuery = "SELECT * FROM biz";
var bizObjects = [];
connection.query(bizQuery, function(err, bizRows) {
if (err) {
throw err;
} else {
for (bizRow in bizRows) {
var bizObject = {};
bizObject['id'] = bizRows[bizRow]['id'];
bizObject['biz_name'] = bizRows[bizRow]['biz_name'];
bizObjects.push(bizObject);
}
}
objects['biz'] = bizObjects;
console.log(objects); // prints the objects
});
console.log(objects); // prints {}
};
var app = express();
app.get("/", function(req, res) {
res.send(getBiz());
});
var server = app.listen(8888, function() {
console.log("Listening........");
});

Your code is synchronous in style when it should be asynchrounous. use callbacks
getBiz = function(onGetObjects) {
var connection = mysql.createConnection({
host:"localhost",
user:"APIUser",
password:"password"
});
connection.query("USE biz");
var bizQuery = "SELECT * FROM biz";
var bizObjects = [];
connection.query(bizQuery, function(err, bizRows) {
if (err) {
throw err;
} else {
for (bizRow in bizRows) {
var bizObject = {};
bizObject['id'] = bizRows[bizRow]['id'];
bizObject['biz_name'] = bizRows[bizRow]['biz_name'];
bizObjects.push(bizObject);
}
}
objects['biz'] = bizObjects;
onGetObjects(objects); // prints the objects
});
console.log(objects); //will definitely print {}
};
function onGetObjects(obj){
this.objects = obj;
console.log(objects) // should give you the correct objects
}
var app = express();
//pass in the callback
app.get("/", function(req, res) {
res.send(getBiz(onGetObjects));
});
var server = app.listen(8888, function() {
console.log("Listening........");
});

Related

NodeJS Array Filter does not get Includes property after pushing object to array

I am trying to create REST API services reading data from Excel. But I can not use the include or indexOf property of Array Filter that is holding data from excel. It shows TypeError: Cannot read property 'includes' of null. I have tried using promise but did not work. Please help me.
var express = require('express');
var http = require('http');
var app = express();
function DeliveryData(Carrier, REF, PRO, ETA, DEL, NAME) {
this.Carrier = Carrier;
this.REF = REF;
this.PRO = PRO;
this.ETA = ETA;
this.DEL = DEL;
this.NAME = NAME;
};
var Excel = require('exceljs');
var workbook = new Excel.Workbook();
var DeliveryRowData = [];
workbook.xlsx.readFile('DeliveryData.xlsx').then(function () {
var worksheet = workbook.getWorksheet('DeliveryData');
worksheet.eachRow({
includeEmpty: false
}, function (row, rowNumber) {
DeliveryRowData.push(new DeliveryData(
worksheet.getRow(rowNumber).getCell(1).value,
worksheet.getRow(rowNumber).getCell(2).value,
worksheet.getRow(rowNumber).getCell(3).value,
worksheet.getRow(rowNumber).getCell(4).value,
worksheet.getRow(rowNumber).getCell(5).value,
worksheet.getRow(rowNumber).getCell(6).value
));
});
});
app.get('/dlv/:id', (req, res) => {
var aaa = [];
var output = '';
console.log(req.params.id);
var results = JSON.parse(req.params.id);
results.forEach(element => {
output = DeliveryRowData.filter(item => item.REF.includes(element));
aaa.push(output);
console.log(output);
console.log(element);
});
res.json(aaa);
});
var server = http.createServer(app);
var port = process.env.PORT || 989;
server.listen(port);

How to set key on request header for authorization in nodejs?

I am beginner in nodejs. I am building a simple server that writes json data to csv file. The question is:
For authorization, the “appKey” parameter needs to be set in the request header:
appKey: 9a3ab6d8-9ffe-49a5-8194-bc7d61123f4a
I could not understand what I am going to do.
This is what I have so far:
var fs = require('fs');
var express = require('express');
var app = express();
var inFilename = 'power_plants.json',
outFilename = 'powerplants.csv';
app.get('/', function (req, res) {
writeToCsv();
res.send('Successfully Created!');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
function writeToCsv(){
var inJSON = fs.readFileSync(inFilename);
inJSON = JSON.parse(inJSON);
var outCSV = inJSON.rows;
var csv = [];
for(var k in outCSV) {
var items = [[outCSV[k].PowerPlant , outCSV[k].meter]];
for (index = 0; index < items.length; ++index) {
csv.push(items[index].join(', ') + '\n');
}
}
fs.writeFile(outFilename, csv, function (err) {
if (err) {
return console.log(err);
}
console.log('FILE SUCCESSFULLY WRITTEN!\n');
});
}
To extract the value of the header appKey you have to get it with this:
var appKey = req.headers.appKey;

Node.JS RemoteExec call not firing properly

Querying a database for a list of servers to perform a command on. The array is populated properly and echos out as planned, but none of the connections occur. I tried both passing the array directly into rexec and looping through a forEachAsync. Neither process the server list properly. Am I referencing the array elements improperly?
Mind the syntax errors at the end, I was just trying to include both methods I tried.
#!
var mysql = require('mysql');
var resultset = require('node-array');
var rexec = require('remote-exec');
var fs = require('fs');
var _ = require('lodash');
//var streamBuffers = require('stream-buffers');
var moment = require('moment');
var util = require('util');
var now = moment().format('YYYYMMDD_HHmmss');
var logStdout = process.stdout;
var errStderr = process.stderr;
console.log = function () {
logStdout.write(util.format.apply(null, arguments) + '\n');
}
console.error = function () {
errStderr.write(util.format.apply(null, arguments) + '\n');
}
var connection = mysql.createConnection({
host : 'abc',
user : 'user',
password : '******',
database : 'db'
});
var ssh_options = {
port: 22,
username: 'e109gh',
privateKey: fs.readFileSync('R:/nodeJS/sshkey.priv'),
stdout: fs.createWriteStream('./out.txt'),
stderr: fs.createWriteStream('./err.txt')
}
var my_conn_options = _.clone(ssh_options);
var cmds = ['hostname -i'];
connection.query('SELECT name FROM server', function(err, rows) {
rows.forEachAsync(function(element, index, array) {
console.log(element.name);
rexec(element.name,cmds,my_conn_options,function(err){
if (err) {
now = moment().format('YYYY-MM-DD HH:mm:ss');
console.error(err);
} else {
console.log("it worked for "+element.name);
}
});
});
});
// var buffer = new streamBuffers.WritableStreamBuffer();
connection.end(function(err) {});
// my_conn_options.stdout = buffer;
//
// rexec(rows,cmds,my_conn_options,function(err){
// if (err) {
// now = moment().format('YYYY-MM-DD HH:mm:ss');
// console.error(err);
// } else {
// console.log()
// }
// });
//
//});

Querying embedded mongodb with node js

I try to fetch a value from my age collection and check by applying the condition if(age===5) then it will fetch data again from other collection question and send the data to the browser. But it will show me the error
Error While Saving the result TypeError: Cannot read property 'age_group_5' of undefined
Code:
1). Node js
var agegroupQuiz = require('../models/agegroupSchema.js');
var questionQuiz = require('../models/question.js');
exports.agegroupController = function(req,res,next){
try{
//var age=5;
var queryObj = {};
var projection1 = '-_id, age_group.age_group_5.max_age';
var projection2 = '-_id question';
//agegropup Schema
var a = agegroupQuiz.findOne(queryObj,projection1);
console.log(a.age_group.age_group_5.max_age);
var age = a.age_group.age_group_5.max_age;
if(age===5){
//question Schema
questionQuiz.find(queryObj,projection2,function(err, data){
if(err){
console.log('getQuestions : Error while getting Questions ' + err);
return next(err);
}
//console.log(question);
res.send(data);
});
}else{console.log("error");}
}catch(err){
console.log('Error While Saving the reuslt ' +err);
return next(err);
}
}
/* exports.agemethod = function(req, res, next){
}*/
2). Mongodb Schema
a). var mongoose = require('mongoose');
module.exports = (function question () {
var Schema = mongoose.Schema;
var question = new Schema({
question:{type:Array,
_id:{type:Number},
title:{type:String},
options:{type:Array},
result:{type:Array},
feedback:{type:String}
},
metadata:{
type:String,
category:String,
age_group:String,
location:String
}
});
var results = mongoose.model('userquestion', question);
return results;
})();
b). var mongoose = require('mongoose');
module.exports = (function agegroup () {
var Schema = mongoose.Schema;
var agegroup = new Schema({
age_group : {
age_group_5: {
_id:{type:String},
max_age:{type:Number}
}
}
});
var results = mongoose.model('age', agegroup);
return results;
})();
I would recommend you try this code and hopefully it should work.
var agegroupQuiz = require('../models/agegroupSchema.js');
var questionQuiz = require('../models/question.js');
exports.agegroupController = function(req,res,next){
try{
//var age=5;
var queryObj1 = {}; //for max age 5
var queryObj2 = {}; //for question
queryObj1 = {
_id: //id,
maxAge: 5 //please put the key in accordance to your schema
};
queryObj2 = {
_id: //id,
question: //question
}
//agegropup Schema
return agegroupQuiz.findOne(queryObj1)
.then(function(maxAge){
var age = maxAge;
if(age == 5){
questionQuiz.find(queryObj,projection2,function(err, data){
if(err){
console.log('getQuestions : Error while getting Questions ' + err);
}
//console.log(question);
res.send(data);
});
}else{
console.log("Error");
}
}).catch(function(error){
console.log('Error While Saving the reuslt ' +err);
});
}
}
I may have missed some curly braces, please verify that, and ignore the indentation.
make sure you use the correct keys of your model.

Javascript value is undefined, function runs after value is assigned

How do I load my variable "vSave" with data. This is where Javascript confuses me. It seems the way I wrote this vSave is undefined when it is returned but I know the response.on('end') runs and has the data I am looking for. I just don't know how to get it returned to my router so I can use it on my client side.
var express = require('express');
var router = express.Router();
var parseString = require('xml2js').parseString;
var config = require('../config_bartapi');
var http = require('http');
var vTemp; // [DEBUG]
var vSave; // [DEBUG]
// Real Time Departure from a given station
router.route('/departTimeStation')
.get(function(req, res) {
var vParsed = '';
vCmd = 'etd';
vOrig = req.query.vOriginStation;
vDir = 'n'; // [NOTE] - 'n' or 's', north or south, OPTIONAL
vPlat = 1; // [NOTE] - 1 to 4, number of platform, OPTIONAL
var xoptions = {
host: 'api.bart.gov',
path: '/api/etd.aspx?cmd=' + vCmd + '&orig=' + vOrig + '&key=' + config.bart.client
};
var xcallback = function(response) {
response.on('data', function(chunk) {
vParsed += chunk;
});
response.on('end', function() {
parseString(vParsed, function(err, result) {
vSave = JSON.stringify(result.root.station);
});
});
};
var vTestHttp = http.request(xoptions, xcallback).end();
return res.send (vSave);
});
// list all BART stations
router.route('/listAllStations')
.get(function(req, res) {
var vParsed = '';
vCmd = 'stns';
var options = {
host: 'api.bart.gov',
path: '/api/stn.aspx?cmd=' + vCmd + '&key=' + config.bart.client
};
var callback = function(response) {
response.on('data', function(chunk) {
vParsed += chunk;
});
response.on('end', function() {
parseString(vParsed, function(err, result) {
vTemp = result.root.stations[0].station;
});
});
};
var vTestHttp2 = http.request(options, callback).end();
return res.send (vTemp)
});
module.exports = router;
Thanks for your help. It seems like an easy concept but I just can't seem to get it.
I had to edit. This is the full bit of code. I originally posted only the one module. Sorry for the extreme edit.
Try to send it in the callback you pass to parseString() function.

Categories

Resources