Reading first line of a text file in javascript - javascript

Let's say I have a text file on my web server under /today/changelog-en.txt which stores information about updates to my website. Each section starts with a version number, then a list of the changes.
Because of this, the first line of the file always contains the latest version number, which I'd like to read out using plain JavaScript (no jQuery). Is this possible, and if yes, how?

This should be simple enough using XHR. Something like this would work fine for you:
var XHR = new XMLHttpRequest();
XHR.open("GET", "/today/changelog-en.txt", true);
XHR.send();
XHR.onload = function (){
console.log( XHR.responseText.slice(0, XHR.responseText.indexOf("\n")) );
};

So seeing as the txt file is externally available ie: corresponds to a URL, we can do an XHR/AJAX request to get the data. Note without jQuery, so we'll be writing slightly more verbose vanilla JavaScript.
var xmlHttp;
function GetData( url, callback ) {
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = callback;
xmlHttp.open( "GET", url, true );
xmlHttp.send( null );
}
GetData( "/today/changelog-en.txt" , function() {
if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 {
var result = xmlHttp.responseText;
var allLines = result.split("\n");
// do what you want with the result
// ie: split lines and show the first line
var lineOne = allLines[0];
} else {
// handle the error
}
});

Related

protractor : passing variable 'url Json file' in executeAsyncScript

I'm new in protractor and I hope to have help regarding how to pass a variable in the executeAsyncScript function used in protractor tests.
I'm testing an application and i need to have a JSON file that contain the labels translation (French and English), at first I could correctly recuperate the language of the user from a first json file(let call getUser.json). Second on depending of the userlanguage I need to pass dynamically the url to get the labels json file (let call lang_fr.json and lang_en.json):
based on the code, 3rd exemple I could access to any json file.
browser.executeAsyncScript(function() {
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
var url='path_to/getUser';
xhr.open("GET", url , true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
};
xhr.send('');
}).then(function(str) {
browser.params.lang=JSON.parse(str)['userLanguage'];
if(JSON.parse(str)['userLanguage']==='fr')
browser.params.url='path_to/lang_en.json';
else
browser.params.url='path_to/lang_fr.json';
UserLanguage.UserLanguage(); /// excuting the fct that call the second jsonfile
now I need to pass the browser.params.urlexecuteAsyncScript to get the json file labels So i do this in another export file:
var url = browser.params.url;
browser.logger.info(browser.params.url); // The url depending the user language is correctly displayed
browser.executeAsyncScript(function() {
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open('GET', url /*here to pass the url depending the user language*/, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
}
xhr.send()
}, url/*passed on second argument*/).then(function(jsonlabel) {
/// rest of the code to resolve the labels
I got that the url is not defined
I checked the following examples:
Executing Async Javascript in Protractor http://blog.ng-book.com/executing-async-javascript-in-protractor/
But in every example I got errors.
So could you please provide me with your suggestion how can I pass correctly the vaiable url in the script? note that when I put the absolute file path it work:
xhr.open('GET', 'path_to/lang_en.json', true);
But I need to pass it dynamically. Hope it's clear and I am here for further details.
So I tried to put the variable url on function(){ and it works!
{
var url = browser.params.url;
var languageUser = browser.params.lang
browser.logger.info(browser.params.url); // The url depending the user language is correctly displayed
browser.executeAsyncScript(function(url /// added here){
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true); xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
}
xhr.send()
}, url).then(function(resJson) {//rest of the code

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.

using XMLHttpRequest to get a web page but only get one part of the html

I use the code below to get a web page(html)
var htmlString=null;
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.yahoo.com");//can change to any web address
xhr.onreadystatechange = function() {
htmlString=htmlString+xhr.responseText;
if(xhr.statusText=="200 OK\r" ){
log (global.htmlString.length);
}
}
but it always get one part of the page, rather than whole html code
Is there any parameter to set the length of the return html code?
Your comment welcome
There will be multiple readystatechange events. The request will only be completely done when xhr.readyState === XMLHttpRequest.DONE === 4.
Also, htmlString = null; ...; htmlString=htmlString+xhr.responseText; is bogus in many ways. First time around it will do htmlString = null + "text" === "nulltext. Afterwards it will add .responseText (as retrieved so far) again and again, while going through the states.
Also, on a related note, you should check xhr.status == 200, not xhr.statusText == randomString. Web servers aren't necessarily sending "OK" in case of 200.
Read the XMLHttpRequest documentation.
Something like this should work better:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.yahoo.com");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 /* DONE */) {
console.log(xhr.responseText.length);
// Do something with it...
}
}
xhr.send();

How to get response from webservice URL using JavaScript

I am new to Javascripting.
I have http webservice URL which results in xml respose. how do I get the response xml from the URL. I tried using the following using XMLHttpRequest but no luck.
function send_with_ajax( the_url ){
var httpRequest = new XMLHttpRequest();
//httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
httpRequest.open("GET", the_url, true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
httpRequest.setRequestHeader("X-Alt-Referer", "http://www.google.com");
httpRequest.send();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4)
{
var _tempRecommendations = httpRequest.responseXML;
window.alert(httpRequest.response)
window.alert(httpRequest.responseText)
window.alert(_tempRecommendations)
}
};
};
I always get httpRequest.readyState = 1 and also when I evaluate the response in console its all null.
According to this: Ajax won't get past readyState 1, why?, you should try to replace your onreadystatechange event by an onload event:
httpRequest.onload= function() {
if (httpRequest.readyState == 4)
{
var _tempRecommendations = httpRequest.responseXML;
window.alert(httpRequest.response)
window.alert(httpRequest.responseText)
window.alert(_tempRecommendations)
}
};
If it doesn't work, try to simplify your code, start with a very basic request like shown here: http://www.w3schools.com/xml/xml_parser.asp for example.
Then start adding request headers, to see which instructions break your program.
You can also check the webservice by calling it directly in the browser to make sure that the problem comes from your side

Read lines from file in array

I have file main.log something like :
10-01-1970 01:42:52 Bus_Power device 9 up
10-01-1970 01:42:52 External_Power device 9 up
10-01-1970 01:42:57 Bus_Power device 1 down
10-01-1970 01:42:57 Bus_Power device 2 down
Every row is one data. How to parse this in array of rows using Dojo or plain JavaScript ?
for example :
['10-01-1970 01:42:52 Bus_Power device 9 up','10-01-1970 01:42:52 External_Power device 9 up']
var xhr = new XMLHttpRequest();
xhr.open('GET', 'main.log', false);
xhr.send(null);
var log = xhr.responseText.split('\n');
// `log` is the array of logs you want
Note: Done synchronously, for simplicity, as no details were given about application of this functionality.
If you have the file into a string (say 'text'), then you can do:
var lines = text.split("\n");
Check if your file on the server terminates lines with just one line-feed (UNIX-style) or a CR-LF pair (Windows-style).
How do you get the file into a string in the first place? You can use dojo.xhrGet(...). Look it up in the Dojo docs.
Say you're reading a text/log file, the following codes are modified from another post of stackflow.com,
var contentType = "application/x-www-form-urlencoded; charset=utf-8";
var request = new XMLHttpRequest();
request.open("GET", 'test.log', false);
request.setRequestHeader('Content-type', contentType);
if (request.overrideMimeType) request.overrideMimeType(contentType);
// exception handling
try { request.send(null); } catch (e) { return null; }
if (request.status == 500 || request.status == 404 || request.status == 2 || (request.status == 0 && request.responseText == '')) return null;
lines = request.responseText.split('\n')
for( var i in lines ) {
console.log(lines[i]);
}
Problems may caused by encoding/decoding issue, so we may need exception handing as well. For more information about XMLHttpRequest, pls visit here.

Categories