Why does the vowel function not return the right value?

Asked

Viewed 94 times

-4

I’m trying to do a function that reads a txt file and returns the number of vowels in the file.

const fs = require('fs');
let texto = "Teste";//tem 2 vogais
fs.writeFile("teste.txt",texto ,(err)=>{
    if(err) {
        throw err;
    }

    console.log("Arquivo salvo");
});

function vogal (file) {
    const letras = ["a", "e", "i", "o", "u"];
    var cont = 1;    
    fs.readFile(file, (err, data) =>{
        if(err) throw err;

        data.toString().split("").forEach(itemTexto =>{
            letras.forEach(itemLetra=>{
                if(itemTexto === itemLetra) cont++;
            });
        });

    });
    return cont;//retorna 1
}

console.log(vogal("teste.txt"));
  • Return consonant size only?

  • 2

    You are counting the vowels, it will only give the right value if there is a very large coincidence in the text. Learn more at this link: https://escolakids.uol.com.br/portugues/consoantes.htm (commented by Maury)

  • @Bacco copying my comment? I did not offend the author of the message. I put that because I was confused.

  • @Maurydeveloper as it was removed, I did not want to lose its relevant link and replenished.

  • No problem. Who removed....

  • I apologize for the mistake, I ended up getting confused with the names, but the goal is to count the vowels. I will edit the question to be clearer.

Show 1 more comment

1 answer

3


You are returning the value of cont before you finish reading your file. As you may already know, Javascript input and output operations are asynchronous, which means that the callback in which you count the characters in your file is the last thing running in your function.

If you want to return the value of an asynchronous process, you have to return within a Promise, or do the console.log within the function itself:

const fs = require('fs')
const util = require('util')

async function consoante(file) {
    // Não me responsabilizo por letras como H, W e Y
    var consoantes = new Set('bBcCdDfFgGjJkKlLmMnNpPqQrRsStTvVwWxXzZ')
    var cont = 0

    var readFile = util.promisify(fs.readFile)
    var buffer = await readFile(file)

    var str = buffer.toString().normalize('NFD')
    for (var c of str)
        if (consoantes.has(c)) cont++

    console.log(`Número de consoantes: ${cont}`)
}
  • "Javascript is asynchronous"?

  • The operations of io sane

  • Yes, but the JS is not :D

  • The edition got better +1

  • Just commenting: The nodejs added the function fs.readFileSync in v0.1.8, but I found the promisify. +1 =D

Browser other questions tagged

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