How can i read txt file line by line - javascript

I want to read txt file line by line, right now it's showing
everything that i have in my file, i want to pass each new line to variable ,how can i do it?
var file = "file:///C:/Users/Viktor/Desktop/test.txt";
function readTextFile(file,line) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status === 0) {
var allText = rawFile.responseText;
}
}
};
rawFile.send(null);
}
readTextFile(file);

You can split the string on the new lines.
var allText = rawFile.responseText,
lines = allText.split(/\n/g); //.split("\n")
console.log(lines.length);

Related

readTextFile function returns undefined. Why?

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
function readTextFile(file)
{
let rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
let allText = rawFile.responseText;
console.log(allText);
}
}
}
rawFile.send(null);
}
readTextFile("/input.txt");
I want to read a txt file and print it to console but I'm getting undefined. What is the reason for that?
const fs = require('fs');
let text = fs.readFileSync('./input.txt');
text = text.toString();
console.log(text);
Use toString() method returns the buffer object.

How to assign the value of toggle button (ngx-toggle) in angular page according to the output of a bash script?

I have an Angular page, where I have a few toggle buttons. The state of those, I have to determine based on the output of a bash script. I'm using ngx-toggle. Now, these toggle button shows if JMS adapters are running on different servers. And I have to take that status from the server.
<ngx-toggle id="devBase" [value]=""></ngx-toggle>
Till now, I've tried to read the status from a text file, but I'm unable to update the value of toggle buttons.
readTextFile(file) {
let rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
let allText = rawFile.responseText;
let lines = allText.split("\n");
let devBase: boolean;
for (let line = 0; line < lines.length; line++) {
if (lines[line].trim() == "devBase=1") {
console.log(devBase);
devBase = true;
}
if (lines[line].trim() == "devBase=0") {
console.log(devBase);
devBase = false;
}
}
}
}
}
rawFile.send(null);
}
When I'm using [(value)]="devBase", it is unable to process.
Two way binding is working. So the html code will be
<ngx-toggle id="devBase" [(value)]="devBase"></ngx-toggle>
The reason it was not working earlier is that the devBase was defined inside a function in my ts file. I returned this value from the function and take it in a universal variable.
readTextFile(file) {
let rawFile = new XMLHttpRequest();
let lines;
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
let allText = rawFile.responseText;
lines = allText.split("\n");
}
}
}
rawFile.send(null);
return lines;
}
And in the outside of this function,
lines: string[];
this.lines = this.readTextFile("http://orapoc06:8087/JavaBridgeTemplate621/dist/assets/files/status.txt");

Javascript filereader onload ( get file from server )

What I want is to read a file from the windows file system or a server so I can display the contents on the website and we are not allowed to use a database or PHP only Javascript.
What I currently have is beneath this and it works if I get the file from a html file upload box the only thing I need is how do I get a file in the javascript without inserting it manually but to load on pageload.
The rest of the code works if I insert the file manually I only need to get a file and insert it into var file = ;
var file = // How do I get file from windows system / or server is also a possibility
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
console.log(lines[line]);
}
};
reader.readAsText(file);
I got it to work
var file = readTextFile("test.txt");
var allText;
var trumpCount = 0;
var hilaryCount = 0;
var reader = new FileReader();
// Entire file
console.log(this.result);
// alert(allText);
// By lines
var lines = allText.split('\n');
for(var line = 0; line < lines.length; line++){
// alert(lines[line]);
if (lines[line].indexOf("t") !== -1){
trumpCount++;
}else{
hilaryCount++;
}
}
alert("Votes for trump: " + trumpCount + " Votes for hilary: " + hilaryCount + " Total votes: " + (trumpCount + hilaryCount))
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)
{
allText = rawFile.responseText;
//alert(allText);
}
}
}
rawFile.send(null);
}

Get undefined callback

I have code like this when I console log the fileContent is gives correct output but when I try to get it as a return it gives error.
I want to use the contents of csv file in other functions.While keeping code clean.
;(function(){
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
var fileContent;
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
fileContent =csvJSON(allText);
return fileContent;
}
}
}
rawFile.send(null);
}
function csvJSON(csv){
var lines=csv.split("\n");
var result = [];
var headers=lines[0].split(",");
for(var i=1;i<lines.length;i++){
var obj = {};
var currentline=lines[i].split(",");
for(var j=0;j<headers.length;j++){
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
return result; //JavaScript object
//return JSON.stringify(result); //JSON
}
var mainContent = readTextFile("main.csv");
})();
You should know a little about asynchronous work. When you set handler to readystatechange you just subscribing to that event from XMLHttpRequest, your function will be called when this event is fire. Therefore this function can not return something back to you. Except if you specify another function called callback and in handler after all call it.
Look at this:
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
var fileContent;
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
fileContent =csvJSON(allText);
callback(fileContent);
}
}
}
And when you want request:
readTextFile('main.csv', function(data) {
console.log(data);
}
This is how asynchronous calculation work.

JavaScript file scanning: get int at certain line

I have a file that looks like this on my server:
0 2
1 8
2 3
3 1
//...
I already know how to get the contents of the file, I do it like this:
var file = 'fileName';
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
}
}
}
rawFile.send(null);
The integer on the left in the file increments for each entry, the integer on the right is random. My program specifies an int n and I want to retrieve the value to the right of the left-hand value that is equal to n. In the example, if program specifies n = 2, I want to get 3. How do I do this?
The more traditional approach of searching line by line
var n = '2', l;
var file = 'fileName';
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText,
lines = allText.split("\n"),
line;
for (var i=0; i<lines.length; i++) {
if (lines[i].indexOf(n) === 0) {
line = lines[i];
break;
}
}
var numbs = line.split(/\s+/);
l = numbs[1];
}
}
}
rawFile.send(null);
One way would be:
var n = 2;
var right = allText.match(new RegExp('^' + n + ' (\\d+)$', 'm'))[1];

Categories

Resources