最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I make a readline await async promise? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Nov 2, 2021 at 15:08 Jason Aller 3,65228 gold badges41 silver badges39 bronze badges asked Nov 2, 2021 at 13:29 LeDucSASLeDucSAS 251 silver badge8 bronze badges 2
  • 1 Node supports top-level await (without need for encapsulation inside an async function) since version 14.3. pprathameshmore.medium./… – Jeremy Thille Commented Nov 2, 2021 at 13:53
  • @JeremyThille true, but at this time you have to define your script/project as type:module, which for existing projects means quite a bit of refactoring (for course, if this is a new script, then it's easy to do). – RickN Commented Nov 2, 2021 at 13:58
Add a ment  | 

3 Answers 3

Reset to default 4

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 () => { ... })();

Wrap the function call into an async IIFE:

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

try this:

async function run(){

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

run();
发布评论

评论列表(0)

  1. 暂无评论