Edit JSON file through loop in node js - javascript

I am making a monitor which will display to a website if a server is up or down. I have tried numerous things including regex, replacement, etc. when it comes to editing the JSON file. I need the "status" in the JSON file to adjust to up or down based upon the 200 responseCode(the status=up/down is just a placeholder for now). Every time I am able to append the JSON file in anyway the text is always added to the bottom of the page outside of the object. It is important to note that this JSON file is used for the front end in the way that displays a green block if the status is 'up', red if it is 'down.' There are also 11 severs in total in my original JSON file.
const config = require(__dirname + '/config/config.json');
var fs = require('fs');
...
function wrapper() {
//FOR EACH SERVER IN CONFIG FILE
for (var server of config.server) {
var url = server.ip + ':' + server.port;
var name = url + " " + server.name;
// DO REQUEST
loadUrl(url, name);
}
}
function loadUrl(url, name) {
var start = new Date().getTime();
request(url, function(error, response) {
var logName = name.split(' ');
var end = new Date().getTime();
var time = end - start;
if (!error) {
console.log(DateTime + " " + name + " " + response.statusCode + " - response time: " + time + "ms");
var total = DateTime + " " + name + " " + response.statusCode + " - response time: " + time + "ms\n";
fs.appendFile("./BY-logs/" + logDates + "_" + logName[1] + ".txt", total, encoding='utf8', function (err) { if (err) throw err; }); //creating or adding to logfile
//CHANGE JSON ACCORDING TO STATUS
if( response.statusCode != 200) {
fs.appendFile('./config/config.json', status = down, function (err) {});
} else {
fs.appendFile('./config/config.json', status = up, function (err) {});
}
}
}
)};
wrapper();
SAMPLE FROM JSON FILE:
{
"port": 3000,
"server": [{
"id": 1,
"name": "abcdefghi2(node-1)",
"ip": "http://123.123.123.12",
"port": "8080",
"status": "up"
}, {
"id": 2,
"name": "abcdefg(node-2)",
"ip": "http://123.123.123.13",
"port": "8080",
"status": "up"
}]
}

You need to load the JSON into the program, change the value of the object, then write it to a file.
Try something along these lines:
var config = require('./config/config.json');
config.server.forEach((server, index, array) => {
if (server.id == "x")
server.status = "up"; // etc.
});
fs.writeFile('./config/config.js', config, (err) => { /* ... */ });
Side note: I would recommened storing your servers as objects inside that object, not an array of objects. This makes it easier to get the server object you want.

Related

How can i get a certain amount of JSON data from an API?

pretty new programmer here, hopefully, this isn't too much of a rudimentary question, just couldn't find the answer anywhere (maybe I just don't know how to look?).
I'm currently working with the BandsInTown API and everything is working great, aside from the fact that I'm receiving way more objects than I need.
I would just like to know if there is a way that I can specify a certain number of objects that I want to receive back?
Any help is appreciated.
require("dotenv").config();
var keys = require("./keys.js");
var request = require('request')
var moment = require('moment')
var media = process.argv.slice(3).join(" ")
function bandsFunct() {
var artist = "";
for (var i = 3; i < process.argv.length; i++) {
if (i !== 3) artist += "-"
artist += process.argv[i];
}
if (process.argv[2] == "concert-this")
request("https://rest.bandsintown.com/artists/" + artist + "/events?app_id=codingbootcamp", function (error, response, body) {
console.log(response.body)
var body = JSON.parse(body)
console.log(" ")
console.log("-------------------------------------")
console.log(" ")
console.log("Upcoming concerts for " + artist + ": ");
for(var set in body) {
var date = moment(body[set].datetime).format("MM/DD/YYYY")
console.log(body[set].venue.city + ", " + "at " + body[set].venue.name + ", " + "on " + date)
}
console.log(" ")
console.log("-------------------------------------")
console.log(" ")
})
}
bandsFunct();
suppose you have a object
let obj = {
{ name: 'war', class :'12' , age: 21, field: 'cse' } ,
{ name: 'jar', class :'120' , age: 251, field: 'csee' }
}
if you want some selected fields you can do like this
var result = Object.keys(obj).filter(item =>
item.class < 100 // you can specify any condition
)
// the result will contain only those objects whose class < 100

selenium screenshots not saving specified directory

I have my selenium test set up to take screenshots, but they are not saving to the directory which I have specified. Can anybody show me what I am missing?
Here is how I am configuring the screenshots in the test:
function writeScreenshot(data, name) {
var fs = require('fs');
name = name || 'ss.png';
var screenshotPath = mkdirp(configuration.readSettings('screenshotDirectory') + fileNameURL + "/", function(err){});
fs.writeFileSync(screenshotPath + name, data, 'base64');
};
and then I take the screenshot:
driver.takeScreenshot().then(function(data) {
var screenshotFile = os + '_' + osVersion + '_' + browser + '_' + browserVersion + '.png';
writeScreenshot(data, screenshotFile);
});
The screenshots end up being saved instead in the projects root directory and with the file name preceded by 'undefined'. (ex. undefinedWindows_8_chrome_46.png)
It does, however, create the folders shown here: var screenshotPath = mkdirp(configuration.readSettings('screenshotDirectory') + fileNameURL + "/", function(err){});
So why is this happening?
mkdirp() is an async method. That is why you pass a callback. You will need to change your code to something like the following:
function writeScreenshot(data, name) {
var fs = require('fs');
name = name || 'ss.png';
var screenshotPath = configuration.readSettings('screenshotDirectory') + fileNameURL + "/";
mkdirp(screenshotPath, function(err){
if (err) {
// something else happened while creating the dir. You decide what to do
return;
}
// Otherwise (if dir was created)
fs.writeFileSync(screenshotPath + name, data, 'base64');
});
};
mkdirp() function is asynchronous - it creates a directory and returns nothing - this is why you having that leading undefined in the filename.
Save the file in the callback:
var screenshotPath = configuration.readSettings('screenshotDirectory') + fileNameURL + "/";
mkdirp(screenshotPath, function (err) {
if (!err) {
fs.writeFileSync(screenshotPath + name, data, 'base64');
} else {
// handle error
}
});
Or, synchronously create the directory and write to it this way:
var screenshotPath = configuration.readSettings('screenshotDirectory') + fileNameURL + "/";
if (mkdirp.sync(screenshotPath)) {
fs.writeFileSync(screenshotPath + name, data, 'base64');
}

Comparing to a user object in ParseQuery and facing error 102

I am trying to find out all the records that matches a user from a Parse class (namely, UserBeaconTracking). I am able to get correct user object and beacon object to begin with. However, when I use the statement
userBeaconTrackingQuery.equalTo("user", user);
Returned Error 102 with an error message "value is expected instead of map type."
What is it that I am doing wrong?
Here is the code snippet:
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo("username", username);
userQuery.find().then(function(currentUser) { // get the user who sent the request
user = currentUser;
console.log("User" + JSON.stringify(user) + "Beacon Name :: " + JSON.stringify(visitedBeaconName));
}).then(function () { // get the beacons with which user communicated
var beaconRelation = Parse.Object.extend("Beacon");
var beaconQuery = new Parse.Query(beaconRelation);
beaconQuery.equalTo("name", visitedBeaconName);
return beaconQuery.find();
}).then(function (beacons) { // get user beacon transaction details
console.log("number of beacons " + beacons.length + " " + beacons[0]);
visitedBeacon = beacons[0];
console.log("beacon :: " + visitedBeacon);
var userBeaconTracking = Parse.Object.extend("UserBeaconTracking");
var userBeaconTrackingQuery = new Parse.Query(userBeaconTracking);
userBeaconTrackingQuery.equalTo("user", user);
userBeaconTrackingQuery.equalTo("beacon", visitedBeacon);
userBeaconTrackingQuery.find({
success : function (results) {
visitCounter = results[0].get("count");
console.log ("Visit Counter :: " + visitCounter);
// get the list of stores associated with the beacon
var beaconTable = Parse.Object.extend("Beacon");
var brandsAssociatedWithBeacon = new Parse.Query(beaconTable);
brandsAssociatedWithBeacon.get(visitedBeacon.id).then(function(beacon) {
typeOfBeacon = beacon.get("type");
console.log("Beacon Type ::" + typeOfBeacon);
var beaconBrandRelation = beacon.relation("brand");
var query = beaconBrandRelation.query();
//return query.find();
});
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
});

How can access the data recieved from API outside of this function

I have used node.js and request.js to access form information from our email services API. With the console.log in the function I am able to see all the info that I need. I have tried to access it outside of the function with dot notation(request.missionStatement) which I don't think is right. I want to be able to display this on a page within an express.js app.
var request = require('request');
// Basic Authentication credentials
var username = "user";
var password = "password";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
// Search for Custom Data Objects Affiliate Falculty form
request(
{
url : "url to api",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
var parsedData = JSON.parse(body);//convert text from API to JSON file
var missionStatement = [];
for (var i = 0; i < parsedData.elements.length ; i++) {
var individualStatement = "";
//Get text submission from form and push into array
individualStatement += (parsedData.elements[i].fieldValues[4].value + ", " + parsedData.elements[i].fieldValues[2].value + " " + parsedData.elements[i].fieldValues[3].value + ", " + parsedData.elements[i].fieldValues[0].value);
missionStatement.push(individualStatement);
};
console.log(missionStatement)
}
);
The variable missionStatement is a local variable declared inside an anonymous function passed as an argument to the request function, and thus it is inaccessible once the anonymous function returns. You must save your result elsewhere. Try something like this:
var request = require('request');
// Basic Authentication credentials
var username = "user";
var password = "password";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
var result;
// Search for Custom Data Objects Affiliate Falculty form
request(
{
url : "url to api",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
var parsedData = JSON.parse(body);//convert text from API to JSON file
var missionStatement = [];
for (var i = 0; i < parsedData.elements.length ; i++) {
var individualStatement = "";
//Get text submission from form and push into array
individualStatement += (parsedData.elements[i].fieldValues[4].value + ", " + parsedData.elements[i].fieldValues[2].value + " " + parsedData.elements[i].fieldValues[3].value + ", " + parsedData.elements[i].fieldValues[0].value);
missionStatement.push(individualStatement);
};
result = missionStatement;
displayResult();
});
function displayResult() {
console.log(result);
}
Your missionStatement will now be saved in result, but only after the anonymous callback to request() has been called (when the actual request is finished).

How do i write(print) to the document from request block in node.js

I wrote some server side code that should get live data from yahoo and then print it to the console and to the browser when i'm running the server, the problem is that i can't find a function that is printing to the document from the request block.
This is my code:
var http = require('http');
var request = require('request');
var cheerio = require('cheerio');
var util = require('util');
tempvar = null;
var server = http.createServer(function(req, res) {
//writing the headers of our response
res.writeHead(200, {
'Content-Type': 'text/plain'
});
// Variable Deceleration
// TODO: move from the global scope
var ticker = "IBM";
var yUrl = "http://finance.yahoo.com/q/ks?s=" + ticker;
var keyStr = new Array();
testTemp = null;
//
// The main call to fetch the data, parse it and work on it.
//
request(yUrl, function(error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
// the keys - We get them from a certain class attribute
var span = $('.time_rtq_ticker>span');
stockValue = $(span).text();
console.log("Stock - " + ticker + " --> text " + stockValue);
//res.write("Stock - " + ticker + " --> text " + stockValue);
testTemp = stockValue;
//
-- end of request --
res.write("Stock value for: " + ticker + " is --> " + testTemp + "\n");
res.write("12333\n");
res.write('something\n');
//printing out back to the client the last line
res.end('end of demo');
## Heading ##
}
});
});
server.listen(1400, '127.0.0.1');
This is the error that i got in the console
Files\node.js\node_modules\YfTemp.js:49 >>;
SyntaxError: Unexpected end of input at Module._compile
at Object.Module._extensions..js at Module.load at Function.Modul._load at Function.Module.runMain at strartup at node.js:906:3
Request works asynchronously. You need to put the printing part of your script inside the request callback block. Otherwise, ticker is not defined yet when the printing lines are reached.
request(yUrl, function(error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
// the keys - We get them from a certain class attribute
var span = $('.time_rtq_ticker>span');
stockValue = $(span).text();
console.log("Stock - " + ticker + " --> text " + stockValue);
//res.write("Stock - " + ticker + " --> text " + stockValue);
testTemp = stockValue;
// -- end of request --
res.write("Stock value for: " + ticker + " is --> " + testTemp + "\n");
res.write("12333\n");
res.write('something\n');
//printing out back to the client the last line
res.end('end of demo');
}
});

Categories