Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
How can I make a readline await async promise?

On NodeJS I need to make a grep like function for log research purposes and I'm trying to make it using readline (since I don't want readline-sync). I've read many messages, tutorials, documentation, stackoverflow posts, and so on, but I couldn't understood how to make it works.

const grep = async function(pattern, filepath){
    return new Promise((resolve, reject)=>{
        let regex = new RegExp(pattern);
        let fresult = ``;

        let lineReader = require(`readline`).createInterface({
            input: require(`fs`).createReadStream(filepath)
        });

        lineReader.on(`line`, function (line) {
            if(line.match(regex)){
                fresult += line;
            }
        });

        resolve(fresult);
    });
}

let getLogs = await grep(/myregex/gi, filepath);
console.log(getLogs);

Which gives me:

SyntaxError: await is only valid in async functions and the top level bodies of modules

Where am I wrong? I feel like I'm good but did a beginner mistake which is dancing just under my eyes.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

What the other answers have missed is that you have two problems in your code.

The error in your question:

Top level await (await not wrapped in an async function) is only possible when running Node.js "as an ES Module", which is when you are using import {xyz} from 'module' rather than const {xyz} = require('module').

As mentioned, one way to fix this is to wrap it in an async function:

// Note: You omitted the ; on line 18 (the closing } bracket)
// which will cause an error, so add it.

(async () => {
let getLogs = await grep(/myregex/gi, filepath);
console.log(getLogs);
})();

A different option is to save your file as .mjs, not .js. This means you must use import rather than require.

The third option is to create a package.json and specify "type": "module". Same rules apply.

A more fundamental issue:

When you call resolve() the event handler in lineReader.on('line') will not have been executed yet. This means that you will be resolving to an empty string and not the user's input. Declaring a function async does nothing to wait for events/callbacks, after all.

You can solve this by waiting for the 'close' event of Readline & only then resolve the promise.

const grep = async function(pattern, filepath){
    return new Promise((resolve, reject)=>{
        let regex = new RegExp(pattern);
        let fresult = ``;

        let lineReader = require(`readline`).createInterface({
            input: require(`fs`).createReadStream(filepath)
        });

        lineReader.on(`line`, function (line) {
            if(line.match(regex)){
                fresult += line;
            }
        });

        // Wait for close/error event and resolve/reject
        lineReader.on('close', () => resolve(fresult));
        lineReader.on('error', reject);
    });
}; // ";" was added

(async () => {
  let getLogs = await grep(/myregex/gi, 'foo');
  console.log("output", getLogs);
})();

A tip

The events module has a handy utility function named once that allows you to write your code in a shorter and clearer way:

const { once } = require('events');
// If you're using ES Modules use: 
// import { once } from 'events'

const grep = async function(pattern, filepath){
    // Since the function is 'async', no need for 
    // 'new Promise()'

    let regex = new RegExp(pattern);
    let fresult = ``;

    let lineReader = require(`readline`).createInterface({
        input: require(`fs`).createReadStream(filepath)
    });

    lineReader.on(`line`, function (line) {
        if(line.match(regex)){
            fresult += line;
        }
    });

    // Wait for the first 'close' event
    // If 'lineReader' emits an 'error' event, this
    // will throw an exception with the error in it.
    await once(lineReader, 'close');
    return fresult;
};

(async () => {
  let getLogs = await grep(/myregex/gi, 'foo');
  console.log("output", getLogs);
})();

// If you're using ES Modules: 
// leave out the (async () => { ... })();
about 4 years ago · Juan Pablo Isaza Relatório

0

Wrap the function call into an async IIFE:

(async()=>{
  let getLogs = await grep(/myregex/gi, filepath);
  console.log(getLogs);
})()
about 4 years ago · Juan Pablo Isaza Relatório

0

try this:

async function run(){

let getLogs = await grep(/myregex/gi, `/`);
console.log(getLogs);
}

run();
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda