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.
CodePudding user response:
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 () => { ... })();
CodePudding user response:
Wrap the function call into an async IIFE:
(async()=>{
let getLogs = await grep(/myregex/gi, filepath);
console.log(getLogs);
})()
CodePudding user response:
try this:
async function run(){
let getLogs = await grep(/myregex/gi, `/`);
console.log(getLogs);
}
run();