skip to Main Content

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


  1. const fs = require("fs").promises;
    
    class Parser {
      async parse(filePath) {
        try {
          console.log(`Trying to open file: ${filePath}`);
          this._file = await fs.open(filePath, "r");
          console.log(`File opened successfully: ${filePath}`);
          this.parseLines();
        } catch (ex) {
          console.log("Error caught in catch block:", ex);
        }
      }
      parseLines() {
        console.log("Parsing lines");
      }
    }
    
    (async () => {
      const parser = new Parser();
      await parser.parse("path/to/nonexistent/file.txt");
    })();

    Try this it should throw error

    Login or Signup to reply.
  2. The issue is that if you have unawaited 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-level await has been available since version 14.8 meaning that all currently supported versions of Node support it. Consider upgrading Node.js.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search