I’m coming pack to Node, trying to use it for some file parsing functionality, but I’m encountering some absolutely bewildering behavior.
I have this parser class that is supposed to open a file then parse it line by line. When I pass it a file path that doesn’t exist, it doesn’t throw an Error but it also doesn’t continue executing. I’ve tried debugging it and the debugger just detaches when I try to continue to a breakpoint I’ve set inside of the catch block. But I also know the open
promise isn’t being fulfilled because it should be at least continuing on to the parseLines
method call where it is supposed to simply print ‘Parsing lines’ to the terminal, but it’s not.
The catch
block is also not running because the error is not being logged to the console either. So the program appears to just be silently dying at this line of code.
I have to be missing something very fundamental.
async parse(filePath: string) {
try {
this._file = await open(filePath, 'r');
}
catch (ex) {
console.log(ex);
}
this.parseLines();
}
private parseLines() {
console.log('Parsing lines');
2
Answers
Try this it should throw error
The issue is that if you have un
await
ed Promises the node.js runtime will not necessarily prevent your program from ending while they’re pending.In this case it sounds like you were calling
process.exit()
explicitly but note this can be an issue even if you’re not.You mention in a comment that you can’t call
await
at the top level, but top-levelawait
has been available since version 14.8 meaning that all currently supported versions of Node support it. Consider upgrading Node.js.