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
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.
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);
Browser other questions tagged node.js
You are not signed in. Login or sign up in order to post.
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 ?
– LeonardoEbert