Javascript: parsed text in var into a set - javascript

I am trying to parse text from a dictionary.txt file for a web browser word game. I found How to read a local text file? and used the readTextFile(file) function the top commentor suggested. However, I don't understand how to get the parsed text into a set.
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText)
}
}
}
rawFile.send(null);
}
alert(allText) gives me a popup with words in the dictionary.txt, so I know the words are getting properly parsed into the variable allText.
How do I now move these words into a set structure for use in my game? I am thinking I would do this in my main program--run readTextFile, then move to set.
Also, as this is my first time using JavaScript, when I run readTextFile in my main program, do I need to do:
myWords = readTextFile("dictionary.txt");
To store allText intomyWords, or will simply doing:
readTextFile("dictionary.txt");
Make it so that I can access allText in my main program? I am unfamiliar with scoping in JS.

I think that all you will need to do is split the text file by new-lines and send the resulting list and instantiate a new Set object with the mentioned list.
Also, check out the documentation on MDN for the Set object.
let myWords = readTextFile("dictionary.txt");
console.log(myWords.has('apple')); // true
console.log(myWords.has('banana')); // true
console.log(myWords.has('carrot')); // true
console.log(myWords.has('durian')); // false
function readTextFile(filename) {
// Blah, blah, blah...
// Code to read the file and return a string...
// Ok, now we have a result:
let result =
`apple
banana
carrot
`;
return new Set(result.split('\n')); // Split the text by new-line and instantiate
}

We will need to know the format of the file to help you parse it. If it is a text file with a word on each line, then you could return allText; in your function, then put it into an array using
var myWords=readTextFile('dictionary.txt').split("\n");

Related

How to get objects from txt file to use in javascript array?

I am very new to coding and javascript; just a few days in. I was wondering if there was a way to import objects from a text file(separated by lines) to use in my array: replyText. Here is what I'm working with:
// Variables
var theButton = document.getElementById("theButton");
var mainText = document.getElementById("mainText");
var replyText = [...,...,...,...,];
var i = 0;
// Functions
function nextText() {
mainText.innerHTML = replyText[i++ % replyText.length];
}
// MAIN SCRIPT
theButton.onclick = function() {
nextText();
};
You can use XMLHttpRequest to get the .txt file just pass the path of it.
var file = new XMLHttpRequest();
file.open("GET", "file:/../file.txt", false);
file.onreadystatechange = function () {
if (file.readyState === 4) {
if (file.status === 200 || file.status == 0) {
var text = file.responseText;
alert(text);
}
}
}
EDIT: you must pass the absolute path file:///C:/your/path/to/file.txt
For client/browser-side file reading:
You cannot easily read a file on the client-side as you are not allowed direct access to the client's file system. However, you can place a input element of file type in your HTML markup via which the client can load a file for your program to process. For example:
<input type="file" id="file" onchange="readFile()" />
Now when the client selects a file for use, the readFile() function will be called which will read and process the file. Here's an example:
function readFile() {
var file = document.getElementById('file').files[0]; // select the input element from the DOM
var fileReader = new FileReader(); // initialize a new File Reader object
fileReader.onload(function() { // call this function when file is loaded
console.log(this.result); // <--- You can access the file data from this variable
// Do necessary processing on the file
});
fileReader.readAsText(file); // Read the file as text
}
For more information on File Reader, check out the docs.
To add on to Paulo's solution, read below for splitting string by line breaks (new line character)
var replyText = text.split("\n"); // "\n" is new line character

How can I set a folder for After Effects to watch for JSON/text files?

I'm successfully using the following extend-script (with json2.js) to read a local JSON file, and change a text layer in my project. How could I modify this script so that, when ran, it continuously 'watches' for new JSON files that are added to the directory, and runs the rest of the script?
#include "json2.js" // jshint ignore:line
var script_file = File($.fileName); // get the location of the script file
var script_file_path = script_file.path; // get the path
var file_to_read = File(script_file_path + "/unique-job-id.json");
var my_JSON_object = null; // create an empty variable
var content; // this will hold the String content from the file
if(file_to_read !== false){// if it is really there
file_to_read.open('r'); // open it
content = file_to_read.read(); // read it
my_JSON_object = JSON.parse(content);// now evaluate the string from the file
//alert(my_JSON_object.arr[1]); // if it all went fine we have now a JSON Object instead of a string call length
var theComposition = app.project.item(1);
var theTextLayer = theComposition.layers[1];
theTextLayer.property("Source Text").setValue(my_JSON_object.arr[2]);
file_to_read.close(); // always close files after reading
}else{
alert("Error reading JSON"); // if something went wrong
}
Look at the Object Model:
Application scheduleTask() method
app.scheduleTask(stringToE xecute, delay, repeat)
Description:
Schedules the specified JavaScript for delayed execution.
So app.scheduleTask(string,delay,true) is exactly what you are looking for.Like this:
app.schduleTask('taskToWatchFile()',1000,true);
function taskToWatchFile(){
/*
*Add your code here
*/
}

Simple AJAX Retrieval of data in XML file, going wrong around ".responseXML"

I've searched and searched and quadruple checked spelling and syntax and I'm stumped. I even checked the syntax on "jslint". I've placed all the code on "jsfiddle":
http://jsfiddle.net/sxtuX/
var xmlHttp= createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function process() {
if (xmlHttp) {
try{
xmlHttp.open("GET", "data_people.xml", true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.send(null);
}
catch (e) {
alert ("In process function.<br/>Error in creating xmlHttp object: "+ e.toString());
}
}
}
function handleStateChange() {
if(xmlHttp.readyState==4) {
if (xmlHttp.status==200) {
try {
handleResponse();
}
catch(e) {
alert ("Trouble getting text." + e.toString());
}
}
else {
alert ("State = "+xmlHttp.readyState+" Status= " + xmlHttp.status);
}
}
}
function handleResponse() {
var xmlResponse = xmlHttp.responseXML,
root = xmlResponse.documentElement,
names = root.getElementsByTagName("name"),
ssns = root.getElementsByTagName("ssn");
alert (xmlHttp.responseText);
var stuff = "";
for(var i=0;i<names.length;i++) {
stuff = names.item(i).firstChild.data + "-" + ssns.item(i).firstChild.data + "<br/>";
}
theD = document.getElementById("theD");
theD.innerHTML = stuff;
}
The javascript works fine up until the last function "handleResponse()" which is the last function. I've placed an "alert" after all the variable declarations using "xmlHttp.responseText" just to prove to myself the file is being accessed and it does print the entire XML file in the alert window.
I tried to create the XML datafile on "jsfiddle" by following the instructions, assuming it was like the HTML file example, but I couldn't get it to work.
So my questions: Why isn't "xmlHttp.responseXML" returning anything? It's either that or something is going wrong with .documentElement. When I examine "names.length" or "ssns.length" they are both zero. Also, can I get some assistance in figuring out the proper way to code an XML file on "jdfiddle" by correcting my fibble attempt?
The way you have your javascript options in the fiddle are set up it only gets executed onLoad (which means all your functions will be defined inside an onload function - and will both not be available in the global scope nor before said function has been executed). It's a catch 22 with sprinkles on top. You'll need to set the second dropdown on the left to either No wrap - in <head> or No wrap - in <body>.
Next up - the jsfiddle example code. There's a whole bunch wrong here:
You should have been referencing Request - not Request.XML (which you just made up ;P). And you should have included the MooTools library (first dropdown on the left) - because that's where Request is from ;)
The url is case sensitive! "/echo/xml/" instead of "/echo/XML/".
The xml string needs to be have properly escaped quotes and javascript strings don't support raw line-breaks (they can be escaped too... but that's another story) - just collapse them for now.
... But you don't need that example. Just use your own code!
Just remember to use the proper test url (with POST not GET) and escape/collapse your test xml.
This is a working fiddle: http://jsfiddle.net/sxtuX/3/

Reading a file line by line backwards

How can I read and print out a plain text file on my server line by line in reverse using javascript? I would prefer to use javascript or jquery over php but have no idea how to accomplish something like this. So for instance if I had a file like
foo
bar
foobar
barfoo
I would like it to print out
barfoo
foobar
bar
foo
Using a http-Request:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
var content = httpGet("google.de"); //enter the Url of your text file here
var lines = content.split("\n");
var result = "";
for(var i=0; i<lines.length; i++)
result = lines[i] + "\n" + result;
alert(result);
Demo is here (displaying the source of http://google.de backwards)
You can do it using the FileReader API. I am not sure if its still in draft or not, but it works in Chrome as well as Firefox.
You will have to simply read the file as text using readAsText method. And then split() the string based on \n and then reverse() and join() again.
Here is a jsFiddle example.

reading a text file line by line using javascript

I am trying to read in lines from a text file that are in this form;
34.925,150.977
35.012,151.034
34.887,150.905
I am currently trying to use this methodology, which obviously isn't working. Any help would be appreciated.
var ltlng = [];
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "C:\Gmap\LatLong\Coordinates.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) {
if (txtFile.status === 200) { // Makes sure it's found the file.
lines = txtFile.responseText.split("\n"); // separate each line into an array
ltlng.push(new google.maps.LatLng(lines.split(",")[0],lines.split(",")[1]); //create the marker icons latlong array
}
}
}
XMLHttpRequest works when resources are called by HTTP/S protocol (and not file protocol, as in your example)
So to make your code work, you should try this code along with a web server

Categories

Resources