Count of new lines in Node

Asked

Viewed 70 times

2

I wish to count the number of new lines of a file. For this I am doing as follows the reading of the file :

const fs = require('fs')//utilizando o módulo fs

fs.readFileSync('<caminhoParaoPrograma>/programa.js')//leitura do arquivo desejado

From this reading of the file, I need a logic to identify the character '\n' and count the total of these in the file. How can I fix this?

1 answer

2

You can use the String.prototype.match, that tests a string using a given regular expression. In this case, we will use the following expression:

/\n/g

That will fetch all line breaks contained in the string.

Something like that:

const text = `L
u
i
z`

const matches = text.match(/\n/g);

console.log(matches.length); // 3

As you can notice above, the match returns an array containing all the strings that correspond to the regular expression. We use the property length to obtain the amount of elements found.

You will then be left with this:

const fs = require('fs');

const contents = fs.readFileSync('<file-name>', 'utf8');
const matches = contents.match(/\n/g);

const count = matches.length; // Use `count` como precisar.
  • Obg for the answer! There was a small error in this solution when using 'const Matches = Contents.match(/ n/g)'. The following error has been returned: 'Typeerror: Contents.match is not a Function'. What can be done to resolve it? Thanks in advance!

  • contents must be a string for the code to work. You must make sure your file is being treated as a string before doing so.

Browser other questions tagged

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