How do I read from position x to position y of a line in Node.js via the readFileSync function?

Asked

Viewed 337 times

1

I have a certain file . txt of which I intend to get some information, but this information is fixed at a certain position of the text line.

1 answer

0


When a text encoding for reading is specified in readFileSync the function returns to the type string instead of being the buffer.

For this reason you can read in the form of string with something like:

const fs = require('fs');
let textoFicheiro = fs.readFileSync("arquivo.txt", "utf-8");

Then you can use the method substring of string to fetch information from a particular location based on positions:

let textoParcial = textoFicheiro.substring(10,20);

Where in the above example you would fetch the position text 10 at the position 19, since the final position is exclusive.

Edit:

To get the contents of the file by lines just do split by the separator of each line \n, or \r\n and then apply the same principles of substring or charAt:

const linhas = textoFicheiro.split("\r\n"); //obter um array de linhas do ficheiro

//obter o caractere para a segunda linha (indice 1) e na posição 10
let caracterLinha2Posicao10 = linhas[1].charAt(10); 

//obter na terceira linha a porção de texto que vai do caractere 15 ao 21
let textoLinha3Pos15_20 = linhas[2].substring(15,21);
  • This works if I only have one line in the string, but in my case I have several lines, and each line will be a different position, as I loop in the string to identify the line I am on ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.