Trying to read a JSON file with a JS script in HTML - javascript

I am trying to use my json file, busesNotArrived.json and put its contents in a <p>, however it is not working and the data in the JSON file is not displaying, here is my code:
<p>Buses Not Arrived:<br><br><span id="output"></p>
<script>
const fs = require('fs')
fs.readFile('json/busesNotArrived.json', 'utf8', (err, jsonString) => {
if (err) {
alert('Error reading Database:', err)
return
}
try {
const bus = JSON.parse(jsonString)
alert("Bus address is:", bus.busNumber)
document.getElementById('output').innerHTML = bus.BusNumber;
} catch(err) {
alert('Error parsing JSON string:', err)
}
})
</script>
Inside of my JSON file, this is what is stored:
{
"busRoute": 123123,
"busNumber": 123123
}

Javascript is not the same as node.js
require() is not a part of JavaScript standard and is not supported by browsers out of the box, it is the node.js module system.
You might need to directly include the modules; some of the modules might not work in the browser sandbox context.
Also, tools such as http://browserify.org/ might be useful.
And please put the error message too.

Well, I eventually figured it out, so like what #Ronnel said, you cannot use require() because that is node.js and not javascript, so you would have to use the fetch() api to get the .json file.
For anyone who would like to see the code, here it is:
<div id="myData" class='absolute1' onclick='notArrived()'><strong><u>Not Yet Arrived</u></strong><br><br></div>
<script>
fetch('json/busesNotArrived.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
var mainContainer = document.getElementById("myData");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML = 'Bus Number: ' + data[i].busNumber + "<br>" + 'Bus Route:' + ' ' + data[i].busRoute + "<br><br>";
mainContainer.appendChild(div);
}
}
</script>
|| Sorry about the Indents :P ||
And also, here is what was in the .json file so you can work off of it:
[
{
"id": "1",
"busNumber": "4024",
"busRoute": "44444"
},
{
"id": "2",
"busNumber": "4044",
"busRoute": "4444"
},
{
"id": "3",
"busNumber": "5024",
"busRoute": "55555"
}
]
Good Luck using this!
If you wanted more explanation, here is where I got the code from:
(https://howtocreateapps.com/fetch-and-display-json-html-javascript/)

Related

uncaught_exception when trying to run a prolog program with Tau-Prolog

i'm trying to use Tau-Prolog integration with javascript via this script:
<!-- index.html -->
<script type="text/javascript" src="tau-prolog.js"></script>
<script>
var TEN_THOUSAND = 10000;
function buttonClick() {
var question = document.getElementById("question-area").value;
if (question == "")
return;
ask(question);
}
function ask(question) {
var session = pl.create(TEN_THOUSAND);
var program = document.getElementById("program").value;
session.consult(program, {
success: function () {
session.query(question, {
success: function (question) {
session.answer({
success: function (answer) {
console.log(answer);
},
error: function (err) {
console.log("ERROR SHOWING THE ANSWER");
console.log(err);
},
fail: function () {
console.log("Query failed.");
},
limit: function () {
console.log("Limit excedeed");
},
});
},
error: function (err) {
console.log("ERROR QUERYING THE PROGRAM");
console.log(err);
},
});
},
error: function (err) {
console.log("ERROR PARSING THE PROGRAM");
console.log(err);
},
});
}
</script>
The prolog program linked to this script is this:
bot(KB, Question, Answer) :-
ask(KB, Question, Answer).
ask(KB, Question, Answer) :-
question(SQ, Question, []),
SQ = action(Action, Modifiers1),
member(action(Action, Modifiers2), KB),
subset(Modifiers1, Modifiers2),
sentence(SQ, Answer, []).
//other predicates
The problem i'm having is that everytime i try to query the bot/3 predicate i get the exception
uncaught exception: error(existence_error(procedure, bot/3, top_level/0)).
I tried running the program on SWI-Prolog, and it works just fine.
I tried to use more simple programs, such as:
member(H, [H | _]).
member(X, [_ | R]) :-
member(X, R).
and it worked.
I'm not using the tau-prolog node.js extension.
Can anyone help? Thanks in advance.

Best place to store JavaScript variable to be easily accessible from Nightwatch tests?

I'm writing a javascript library and when some event happens I would like to store a JSON variable that can be accessed from NightwatchJs tests to validate the data that the event generated.
I used to store it as a global variable (ex.
window.debugLog = { message: "something", timestamp: 1111, eventType: "click", other: "stuff" }; )
and retrieve it in nightwatch with
browser.execute("return window.debugLog;", [], function(result){ debugLog = result.value;})
Unfortunately this doesn't seem reliable with every browser/device when I run Nightwatch tests over Browserstack. It's not rare to have false positives because Appium failed to execute the Js function.
I was wondering if anyone has suggestions about more reliable alternatives. A cookie? A metatag? An hidden tag?
Write it to a file, require that file for the later tests that use it.
I have, in the custom_commands folder, a file called helperFunctions.js, and within that, this is one of the more useful functions/methods:
saveToFile : function(client, path, data) {
this.fs = fs;
buffer = new Buffer(data);
fs.open(path, 'w', function(err, fd) {
if (err) {
throw 'error opening file: ' + err;
}
fs.write(fd, buffer, 0, buffer.length, null, function(err) {
if (err) throw 'error writing file: ' + err;
return fs.close(fd, function() {
console.log('File write: ' + path + ' has been updated.' );
})
});
})
},
In that way it can be called to write data from within any test:
this.helperFunctions.saveToFile(client, "conf/usefulVariable.js", "module.exports = {\"default\" : {},\"test_env\" : { myGlobal: " + someGlobal + "}};")
In the test file that needs to use it:
var usefulVar = require("../conf/usefulVariable.js");
You may need/want to JSON.stringify or parse as appropriate.

NodeJS won't Properly load other Files [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm having trouble getting my NodeJS server to properly return the auxiliary files an HTML files needs. Instead of returning them to their appropriate places within the files, it does something really screwy.
Here's the code in question:
index.js:
var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');
var findFile = (function(basename) {
var results = {
contentType: '',
data: ''
};
var dataCSS = {
dir: '../CSS/',
contentType: 'text/css'
};
var dataHTML = {
dir: '../HTML/',
contentType: 'text/html'
};
var dataJS = {
dir: '../JS/',
contentType: 'text/javascript'
};
return function(basename) {
switch (path.extname(basename)) {
case '.css':
fs.readFile(dataCSS.dir + basename, function(err, data) {
results = {
contentType: dataCSS.contentType,
data: data
};
});
break;
case '.html':
fs.readFile(dataHTML.dir + basename, function(err, data) {
results = {
contentType: dataHTML.contentType,
data: data
};
});
break;
case '.js':
fs.readFile(dataJS.dir + basename, function(err, data) {
results = {
contentType: dataJS.contentType,
data: data
};
});
break;
default:
fs.readFile(dataHTML.dir + 'Home.html', function(err, data) {
results = {
contentType: dataHTML.contentType,
data: data
};
});
break;
}
return results;
};
})();
http.createServer(function(req, res) {
var myUrl = url.parse(req.url);
var basename = path.basename(myUrl.path);
console.log('request url: ' + req.url);
if (req.url !== '/') {
console.log('File requested: ' + basename);
} else {
basename = "Home.html";
}
console.log("Basename: " + basename);
var data = findFile(basename);
console.log(data);
res.writeHead(200, { 'ContentType': data.contentType });
res.write(data.data);
res.end();
}).listen(8080);
Home.html:
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="../CSS/myApp.css">
<script src="../JS/myApp.js"></script>
<script src="../JS/myCtrl.js"></script>
</head>
<body>
<h2>myApp Test</h2>
<div class="myApp" ng-app="myApp" ng-controller="myCtrl" ng-init="quantity = 10; cost = 5" my-Directive>
<p>Color: <input type="text" style="background-color:{{myColor}}" ng-model="myColor" value="{{myColor}}"></p>
<p>Total in dollar (raw exp): {{quantity * cost}}</p>
<p>Total in dollar (span): <span ng-bind="quantity * cost"></span></p>
<p> First Name: <input type="text" ng-model="firstName"></p>
<p> Last Name: <input type="text" ng-model="lastName"></p>
<h1>Hello, {{firstName + " " + lastName}}</h1>
</div>
Are you even changing?!
</body>
</html>
A current run of my code does this:
I use "node index.js" in the console to start the server.
I navigate to "localhost:8080" in my browser for the first time, it shows nothing; there's an error in the dev window that says that I did not format the headers properly. This isn't true since I set it in the findFile method on each hit to the server. A console readout first looks like this:
The dev window in Firefox looks like this:
The next refresh loads the HTML page, but without any influence from the auxiliary files, even though the logging shows everything has been requested:
console log at this point:
Subsequent refreshes turns the page into a roulette with each of the separate files representing a number on the wheel. Instead of the HTML page, one of the others might display instead, with the looks of a text file. I'll spare the pictures; I feel like I've done too many as it is.
What am I doing wrong here? Is there a different way I should be doing this? Should I even have to do this at all? Please send help.
Thank you.
fs.readFile is asynchronous, meaning the callback you give to it doesn't happen immediately, it happens sometime later. Particularly, it happens after the findFile function returns the value. See this related question for more details.
In order for findFile to work correctly, it needs to receive a callback to call whenever any of the fs.readFile operations are finished. Also look into promises and async/await as a cleaner alternative to using callbacks.
function findFile(basename, done) {
switch (path.extname(basename)) {
case ".css":
fs.readFile(dataCSS.dir + basename, function(err, data) {
var results = {
contentType: dataCSS.contentType,
data: data,
}
// this function is the `function(results)` we call with down there
done(results)
})
break
case ".html":
// same as above
case ".js":
// same as above
default:
// same as above
}
}
function requestHandler(req, res) {
// same as before
findFile(basename, function(results) {
console.log(results)
res.writeHead(200, { ContentType: results.contentType })
res.write(results.data)
res.end()
})
}
http.createServer(requestHandler).listen(8080)

Load JSON file from local PC in Nativescript

So I am having trouble displaying the contents of my JSON file in nativescript using console commands.I basically want to display these contents and use the values in the file to do some additional functions.
This is the JS function that I have slightly rewritten from the NS documentation and Emil Oberg's solution on a different post
var fs = require('file-system');
var documents = fs.knownFolders.documents();
var jsonFile = documents.getFile('/Users/student/Desktop/Native_Script/Library/app/images/status.json');
var array;
var jsonData;
//console.log('Item:' +jsonFile);
jsonFile.readText()
.then(function (content)
{
try {
jsonData = JSON.parse(content);
//console.log('Item:' + JSON.stringify(jsonData));
array = new observableArrayModule.ObservableArray(jsonData);
}
catch (err) {
console.log(err);
}
console.log('Item:' +JSON.stringify(jsonData));
});
////////////////
JSON File:
[{
"Status": "3",
"Trend": "increase",
"Space": "Gleason"
}, {
"Status": "2",
"Trend": "decrease",
"Space": "PRR"
}, {
"Status": "4",
"Trend": "stable",
"Space": "WBR"
}, {
"Status": "1",
"Trend": "decrease",
"Space": "HCR"
}]
So can someone tell where I am going wrong and how would I go about displaying any of the components of the file in the console. I essentially want to use one of the values in the file, say status, to call on another function.
So something like: (psuedocode)
status.getvalue
.then(function)
if status > 3
console.log (place is crowded)
Okay so here you're trying to read a file on your computer, from a device (iPhone/Android/Emulator/etc). This is simply not doable. The getFile call expects a path on the device.
So, either:
Store the JSON file on the device, or
Just require() the JSON file. E.g. var jsonFile = require('status.json') and it'll get read and parsed for you.
Add something like below code, might be your jsonFile.readText() is throwing error
p1.then(function(value) {
console.log(value); // "Success!"
throw 'oh, no!';
}).catch(function(e) {
console.log(e); // "oh, no!"
})
jsonFile.readText()
.then(function (content)
{
try {
jsonData = JSON.parse(content);
//console.log('Item:' + JSON.stringify(jsonData));
array = new observableArrayModule.ObservableArray(jsonData);
}
catch (err) {
console.log(err);
}
console.log('Item:' +JSON.stringify(jsonData));
})
.catch(function(e) {
console.log(e); // "oh, no!"
});

how to customize angular toaster message

I am using angular-file-upload. I have setup a batch file upload that parse's the file names and matched them to properties stored in a database. The files need to be structured like this.
01-1998 VRF RD678.pdf
VRF is the name of a pipeline
RD is the name of a location
678 is the number of a location code
they each have there own if statement to check for files that do match anything in the database. right now if something does not match or is named improperly this appears
I would like to do 3 things.
define a error message that shows the file name and the specific if statement that errors out. if there is no match for the pipeline i want the file name and "no match for pipeline" underneath.
define a error message for when the structure of the file name is incorrect. i want the file name with "incorrect filename" underneath
prevent the function from error out, I would like the error messages to be displayed and allow the other files to be uploaded
I am trying to use linq.js, javascript is ok as well.
here is what i am trying to make work, this example is when a file is not structured correctly. this error message is
TypeError: Cannot read property 'name' of undefined
$scope.upload = function () {
var files = $scope.files;
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
$scope.pipes.map(function (pip) {
$scope.pipeLookup[pip['PipeAb']] = pip;
});
$scope.locations.map(function (loc) {
$scope.locationLookup[loc['LocationAb']] = loc;
});
$scope.locationCodes.map(function (locCode) {
$scope.locationCodeLookup[locCode['LocationCodeAb']] = locCode;
});
var matchesPip = file.name.match(/^\d+\D\d+\s*(\S*\s*)(\S*)/i);
var matchesLoc = file.name.match(/^\d+\D\d+\s*?(\S*)\s*(\S*?)(\d+)\./i);
var matchesLocCode = file.name.match(/^(\d+\D\d+)\s*?(\S*)\s*(\S*?)(\d+)\./i);
$scope.pip = $scope.pipeLookup[matchesPip[1]];
$scope.loc = $scope.locationLookup[matchesLoc[2]];
$scope.locCode = $scope.locationCodeLookup[matchesLocCode[4]];
if ($scope.pip == null) {
$scope.pip = Enumerable.From(files)
.Where("x => x.files.name != '" + matchesPip[0] + "'").ToArray();
toaster.pop('error', matchesPip[0]);
console.log(matchesPip[0])
}
if ($scope.loc == null) {
toaster.pop('error', matchesLoc[0]);
console.log(matchesLoc[0])
}
if ($scope.locCode == null) {
toaster.pop('error', matchesLocCode[0]);
console.log(matchesLocCode[0])
}
$upload.upload({
url: '/api/apiBatchPipeLine',
fields: {
'typeId': 1,
'companyId': $scope.companyId.CompanyId,
'companyName': $scope.companyId.CompanyName,
'documentDate': $scope.model.documentDate,
'pipeId': $scope.pip['PipeId'],
'pipeName': $scope.pip['PipeName'],
'locationId': $scope.loc['LocationId'],
'locationAb': $scope.loc['LocationAb'],
'locationCodeId': $scope.locCode['LocationCodeId'],
'locationCodeAb': $scope.locCode['LocationCodeAb']
},
file: file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
}).success(function (data, status, headers, config) {
toaster.pop('success', config.file.name);
console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
}).error(function (err, result, config) {
toaster.pop('error', config.file.name);
console.log(err, result);
});
}
}
};
ngFileUpload error event callback receives 4 arguments as in:
https://github.com/danialfarid/ng-file-upload/blob/master/dist/ng-file-upload-all.js#L509-514
promise.error = function (fn) {
promise.then(null, function (response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
headers is the 3rd argument, config is the 4th argument. In your code config is referencing headers. headers.file is undefined so this is how you get the error TypeError: Cannot read property 'name' of undefined.
Change:
.error(function (err, result, config) {
...
})
To:
.error(function (err, result, headers, config) {
...
})

Categories

Resources