Navigate through a JavaScript text file one line at a time

There is a text file with the following content:

User:root
Password:root123

My goal is to read this text file in JavaScript line by line and store it in an array. Then, I want to split each value in the array using a colon (:).

Despite trying multiple approaches, I haven't been successful in achieving this.

xmlHttp.onreadystatechange = function() {
  var tmpDoc, re=/^(.+)$/gm, arr=[], oP, arrSplit=[], arrSpl=[];
  if(xmlHttp.readyState === 4) {
    if(xmlHttp.status === 200){
      alert("AS");
      tmpDoc = xmlHttp.responseText;    
      arrSpl = tmpDoc.split(",");
      var arrGlobalHost = arrSpl[0].split(':');
      var arrGlobalUser = arrSpl[1].split(':');
      var arrGlobalPass = arrSpl[2].split(':');
      strGlobalHost = arrGlobalHost[1];
      strGlobalUser = arrGlobalUser[1];
      strGlobalPass = arrGlobalPass[1];
      xmlHttp=null;
    }
  }
}; 
xmlHttp.open("POST", fileName, true); // Use POST to prevent use of cached file
xmlHttp.send(); 

I have attached this function to a button click event, but I'm not getting the desired output on the first click. Since the ready state is only maintained after the page has loaded for the first time, I now need to load the page for the first time itself to ensure it works as intended.

Answer №1

When it comes to Windows, one can use JScript + ActiveXObject("Scripting.FileSystemObject")

http://msdn.microsoft.com/en-us/library/2z9ffy99(v=vs.84).aspx

var fso, f1, ts;
var ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CreateTextFile ("c:\\test1.txt");
f1 = fso.GetFile("c:\\test1.txt");
ts = f1.OpenAsTextStream(ForWriting, true);
while (!ts.AtEndOfStream()) {
   var line = ts.ReadLine();
}

For other platforms, such as Node.js, one can utilize Node.js + "File System"

http://nodejs.org/api/fs.html

http://nodejs.org/api/stream.html#stream_class_stream_readable

var fs = require('fs');
var readable = fs.createReadStream('sample.txt', {start: 90, end: 99});
readable.on('data', function(chunk) {
  console.log('got %d bytes of data', chunk.length);
});

Answer №2

Downloaded from the internet

<!DOCTYPE html>
<html>
<head>
<script     src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
   $("#div1").load("demo_test.txt");
});
});
</script>
 </head>

<div id="div1"><h2>Allow jQuery AJAX to Edit This Text</h2></div>
<button>Retrieve External Content</button>

Suggestion, utilize search engines

Answer №3

My unique method involves manipulating the text file (config.txt) by using commas as separators.

User:root,
Password:root123

In addition, I implemented a hidden field named 'user' to capture the response from a file read through AJAX. Below is the code snippet I utilized:

var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "config.txt", false);
xmlHttp.send(null);
var result = document.getElementById('user').value;
var result = xmlHttp.responseText;
var arrSplt = new Array;
arrSplt = result.split(',');
var arrSplittedCredHost = new Array;
var arrSplittedCredUser = new Array;
var arrSplittedCredPass = new Array;
arrSplittedCredHost = arrSplt[0].split(':');
arrSplittedCredUser = arrSplt[1].split(':');
arrSplittedCredPass = arrSplt[2].split(':');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to easily open the RSS link XML Element in a separate browser tab or window?

I have been exploring RSS and creating titles with links. However, when clicking on the link it opens in the same window. I would like it to open in a new window instead. Can someone please advise me on how to achieve this? <a href="http://www.google ...

Having trouble with Vue component not updating Vuex state before it loads?

At times, the token is committed to Vuex store while other times it is not. userLogin() { axios.post('api/login', this.logindata,) .then(response => { let token = JSON.parse(localStorage.getItem('token')); t ...

Top methods for identifying AJAX/XmlHttpRequest compatibility

I am in the process of updating an old JavaScript function that checks for support for AJAX (specifically, the XmlHttpRequest object). While searching online, including on SO, I came across various solutions but I'm uncertain about which one is the mo ...

Modifying properties of an array of objects in React Native using JavaScript

I have a scenario where I am using Flatlist to render a couple of boxes. If the "shapes" element's "visible" key is false, the box will be blank. This visibility property is defined in state and I'm not sure if this is the correct approach. Now, ...

Tips for exporting 3D objects from 3ds Max Studio for optimal use in Three.js

I am facing an issue with loading a 3D object that I created in 3D Studio Max! When I export it as a .obj file (which generates two files, .obj and .mtl), I have tried using OBJMTLLOADET(), MTLLOADER(), and OBJLOADER() but none of them seem to work. Other ...

Differences seen in display when using Internet Explorer's prependTo feature

Here is some code that I am working with:- <ul id="list1"> <li class="a">item 1</li> <li class="a">item 2</li> <li class="b">item 3</li> <li class="b">item 4</li> </ul> Additiona ...

Wordpress problem with Bootstrap JavaScript code involving data-toggle="collapse"

Currently facing an issue with my project. This is my first attempt at creating a WordPress blog, inspired by the HTML site www.humantools.com.mx and building a blog for it at www.humantools.com.mx/blog. There's a strange problem: when logged in, the ...

Tips on formatting dates in a Material UI text field

<TextField name="BalDueDate" format="MM/dd/yyyy" value={basicDetails.BalDueDate.slice(0,10)} onChange={event => { ...

An anomaly where a mysterious symbol appears in front of every dollar sign in an HTML document

I have a code written in AngularJS to display the amount in dollars. However, there is an unwanted " Â " character appearing before every " $ " character in the HTML. I am looking for a way to remove this character. Your help is greatly appreciated. Thank ...

Troubleshooting AngularJS Get Function Failure

New to the world of AngularJS, I find myself faced with a challenge. My .NET MVC WebAPI Restful app is up and running on an IIS server. However, when I attempt to query the API using , the response I receive is: [{"Id":1,"Name":"Glenn Block","Created":"00 ...

Tips for activating swf file autoplay on the mobile edition of WordPress

I recently added a swf file to my WordPress page (https://www.pacifictintlv.com/mobile). However, I have noticed that it does not seem to work properly when viewed on mobile devices. Is there a way to redirect users to the Flash download link if they do ...

Can anyone suggest a more efficient method for detecting expired SESSIONS in JQuery?

After only a few weeks of using JQuery, I've encountered an issue where my login page loads within the existing document when the SESSION expires. This problem never occurred before I started using JQuery. It seems that since I have converted all my d ...

What is the best way to retrieve router parameters within a JSX component?

How can I pass the post ID as a prop to the EditPost component in order to edit it? render() { return ( <Router> <Switch > <Route path="/edit/:id"> <EditPost index={/*what do I do here?*/} /> ...

Setting up a reverse proxy for deploying React applications

I am attempting to implement a setup where multiple containerized SPAs are deployed using a reverse proxy for routing. Each container contains a production build create-react-app served by an express app with the following configuration: app.use(express.s ...

There may be instances where data is null in Java Spring and React JS

My goal is to store all data using react.js and Java Spring. I have sent data via REST, but one of the data classes is coming up as null in the MongoDB collections. I have checked to ensure that all data types are the same but I am unable to identify and r ...

Ensuring that the initial column of a table remains in place while scrolling horizontally

Thank you for taking the time to read this. I am currently working on a table within a div container (div0) where the data is dynamically generated, resulting in a table with unpredictable height and width. The outer div allows for both vertical and horizo ...

Is there a way to modify my code to restrict users from liking a post multiple times?

I am currently working on a like system and I have made some progress. However, I am struggling to make it so that the likes only increment once. Does anyone have any insights or suggestions on how to achieve this? I have considered using session variables ...

Where can I locate a specific child element in this scenario?

Currently, I am exploring the possibilities of integrating AngularJS into my application and have encountered a question regarding the click event implementation. Within my HTML code: <div ng-click='clickMe()' ng-controller='testCtrl&ap ...

Utilizing dynamic components in React JS

I'm a beginner in React JS and I'm facing an issue where I'm trying to call a React component from an HTML string that is being generated by another JavaScript class. However, the component is not rendering on the screen. class Form extends ...

Starting data initialization using a property object within a Vue component

I am encountering an issue with two Vue components, EventTask and EventCard. Within EventTask, there is a currentEvent object in the data section, which I pass as a prop to EventCard using the following code snippet: <event-card :current-event="cur ...