How to load a text file in JavaScript? - javascript

I'm creating a simple WebGL project and need a way to load in models. I decided to use OBJ format so I need a way to load it in. The file is (going to be) stored on the server and my question is: how does one in JS load in a text file and scan it line by line, token by token (like with streams in C++)? I'm new to JS, hence my question. The easier way, the better.
UPDATE: I used your solution, broofa, but I'm not sure if I did it right. I load the data from a file in forEach loop you wrote but outside of it (i.e. after all your code) the object I've been filling data with is "undefined". What am I doing wrong? Here's the code:
var materialFilename;
function loadOBJModel(filename)
{
// ...
var req = new XMLHttpRequest();
req.open('GET', filename);
req.responseType = 'text';
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line)
{
readLine(line);
});
}
}
req.send();
alert(materialFilename);
// ...
}
function readLine(line)
{
// ...
else if (tokens[0] == "mtllib")
{
materialFilename = tokens[1];
}
// ...
}

You can use XMLHttpRequest to fetch the file, assuming it's coming from the same domain as your main web page. If not, and you have control over the server hosting your file, you can enable CORS without too much trouble. E.g.
To scan line-by-line, you can use split(). E.g. Something like this ...
var req = new XMLHttpRequest();
req.open('GET', '/your/url/goes/here');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line, i) {
// 'line' is a line of your file, 'i' is the line number (starting at 0)
});
} else {
// (something went wrong with the request)
}
}
}
req.send();

If you can't simply load the data with XHR or CORS, you could always use the JSON-P method by wrapping it with a JavaScript function and dynamically attaching the script tag to your page.
You would have a server-side script that would accept a callback parameter, and return something like callback1234(/* file data here */);.
Once you have the data, parsing should be trivial, but you will have to write your own parsing functions. Nothing exists for that out of the box.

Related

How to use JSON data to create an array

Okay so I want to be able to take a JSON file (external) and process it so that I can create an array that I can use to display the data.
JSON.parse() only works if I declare the JSON array then parse it, it does not work for external JSON data
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
console.log(JSON.parse(this.responseText.replace(/[u2018\u2019\u201c\u201D]/g,'"')));
document.getElementById("here").innerHTML =
console.log(myObj.Cardionotes[0].note);
}
}; xmlhttp.open("GET", "PATIENT51.txt", true);
xmlhttp.send();
};
I've used this question for help but I'm getting the same error- JSON.parse Error: Invalid character at position:3 (that's the middle of the if)
How do I turn a JSON file into an arraylist
Just use fetch() (or use a library like umbrella or jQuery) instead of trying to use AJAX without a library, you will want to bang your head into a wall once you discover all the problems there are with different implementations across browsers...:
const response = fetch('https://www.reddit.com/r/json.json')
.then((data) => {
// do your .replace(/[u2018\u2019\u201c\u201D]/g,'"') here, e.g.
// data.replace(/[u2018\u2019\u201c\u201D]/g,'"').json();
return data.json();
})
.then((json) => {
console.log(json);
})
.catch(err) => {
console.log(err);
});

How to save javascript variable or console.log(variable) to a file

I am using node and I have some code that I run that puts the data from an API call out in a certain JSON format I need for dynamo. It is about 23000 records or so a day and I am attempting to save them to my hard drive. Can someone please let me know how to save the output of a variable to a file? I have seen other pages on here but most of them seem to cover an html element with onclick or something along those lines. I appreciate any help.
In node to write in a new file or replace old
var fs = require('fs'); // reqire fileSystem node module
fs.writeFile("pathToFile", "Content", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
Or append to existing file
fs.appendFile("pathToFile", "Content", function (err) {
if (err) throw err;
console.log('Saved!');
});
One of the most common ways to log something from JavaScript is to use AJAX to post the value of the JavaScript variable. You can use any server-side script, including Node's FileSystem API to save a log of the variable to a specific file.
Example:
function saveVariable(variable) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("Saved");
}
};
xhttp.open("POST", "save?var=" + variable, true);
xhttp.send();
}

How to retrieve a html file content and insert to another html file?

I am trying to write templates for a mobile app, as I only know pure JavaScript, so my plan is replacing the default template with a new one. After few hours I was nearly exhausted on this issue. It is not CORS thing and all the files are in localhost.
function getTheme(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "model/1/index.html", true);
xhr.responseType = "document";
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0) {
var customTheme = document.getElementById('crapDiv');
customTheme.innerHTML = xhr.responseXML;
}
}
}
xhr.send(null);
}
This Ajax works quite fine when I test with a text file, but as MDN said, to retrieve a html with ajax, a "document" responseType must be declared, thus, with the xhr.responseXML it only returns a DOM object, which is [object HTMLDocument]
I just can not parse this object back into contents so that I could not insert it into another html file.
So, How could I get through with this issue plz? and, plz only pure JS code.
You can't edit a file's content with JavaScripts, you can only read it. It's not for that. You need a server with eg PHP that can save your data.
You can get the response data as raw text with xhr.responseText.
Finally I got it.
function getTheme(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "model/1/index.html", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0) {
var customTheme = document.getElementById('crapDiv');
customTheme.innerHTML = xhr.responseText;
}
}
}
xhr.send(null);
}
The diff is just the declare of the responseType, by default it is "", and xhr.responseText is the right way to retrieve the content, while the xhr.responseXML is the right way to retrieve the DOM object.
As it should be xhr.responseText, so there is no more need to declare responseType, and must be "" or "Text" if you still want a decalration.
Thnx.

Sending data from javascript to php file

I have this function that gets text from a php file on the server and plonks it into an HTML page.
What changes do I need to make to it to SEND data (just a couple of javascript variables) to the php file rather than read from it ? Hoping not many !!
function process() {
if (xmlHttp) // the object is not void
{
try {
xmlHttp.open("GET", "testAJAX.php", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch (e) {
alert(e.toString());
}
}
}
Take a look at what all headers you can make use of. In your case, you would want to use POST instead of GET
xmlHttp.open("POST", "testAJAX.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//or JSON if needed
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(data);
You are probably better of using POST to send data it has less limitations. e.g:
var data = {
user: 'Joe',
age: 12
};
var httpReq = new XMLHttpRequest();
// true means async - you want this.
httpReq.open('POST', 'testAJAX.php', true);
// json is just a nice way of passing data between server and client
xmlhttpReq.setRequestHeader('Content-type', 'application/json');
// When the http state changes check if it was successful (http 200 OK and
// readyState is 4 which means complete and console out the php script response.
httpReq.onreadystatechange = function () {
if (httpReq.readyState != 4 || httpReq.status != 200) return;
console.log(httpReq.responseText);
};
httpReq.send(JSON.stringify(data));
And read it:
$name = json_decode($_POST['name']);
$age = json_decode($_POST['age']);
If it's just a couple of variables, you can pop them into the query string - although you'll want to make sure their values won't break your PHP script or open a security hole (for example, don't interpret user input as a SQL string). For more complicated data structures, use POST as others have suggested.
function process(var1value, var2value) {
if(xmlHttp) {
try {
xmlHttp.open("GET", "testAJAX.php?var1="+var1value+"&var2="+var2value, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch(e) {
alert(e.toString());
}
}
}

Use XMLHttpRequest to read data after a period of time - Chrome Extension

I'm using XMLHttpRequest to read a text file (on local) after a period of time (after 10s).
After 10s, XMLHttpRequest retrieves the text file but the content (responseText) does not changed even though I have changed it.
Here is my code:
var list = [];
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText.length == 0) {
undef();
}
else {
def();
}
}
}
getFile();
function getFile() {
list = [];
xhr.open("GET", chrome.extension.getURL('text/list.txt'), true);
xhr.send(null);
}
var myVar = setInterval(function(){getFile()}, 10 * 1000);
function def() {
// do something
}
function undef() {
// do something
}
I don' know why and how to fix it, please help.
The fast/lazy solution is to change your link address without changing the file it's accessing.
Modify your link with LinkToFile+"?="+Math.random()
It won't match anything in the cache but it will fetch the same file.
I found the problem, it is that the folder containing the file that I use when coding is different from the folder containing the extension when added to Chrome.
I just modified the wrong file.
Thank you everyone for your help.

Categories