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

1

I have a certain .txt file that I want to get some information, but this information is fixed in a certain position of the text line.

    
asked by anonymous 04.08.2017 / 22:06

1 answer

0

When a text encoding for reading is specified in readFileSync , the function return becomes type string instead of being type buffer .

For this reason you can read as string with something like:

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

You can then use the substring method of string to fetch information from a given location based on positions:

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

In the above example I would look for the text from position 10 to position 19 , since the final position is exclusive.

Edit :

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

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);
    
05.08.2017 / 01:46