lucagrulla / node-tail

The zero dependency Node.js module for tailing a file
https://www.lucagrulla.com/node-tail/
MIT License
467 stars 76 forks source link

Update tail.js #128

Closed andrewnguyen92 closed 3 years ago

andrewnguyen92 commented 3 years ago

Removing the error thrown in "latestPosition()". The application is can't catch this exception so it'll crash. An example scenario would be to tail a file and then delete the file from the system.

lucagrulla commented 3 years ago

Hi @andrewnguyen92 ,

In that scenario, when the library cannot access the underline file anymore, rethrowing the exception is the expected behaviour.

If the exception is just swallowed, tail could stay stuck forever (no file to read but also no exiting).

Can you share your specific scenario where swallow the exception would be better?

andrewnguyen92 commented 3 years ago

Hi Luca, would that case be handled by the previous line that emits the error event? I am running tail on a file that may get deleted and recreated shortly thereafter in the background. Removing this exception throwing and setting up an event handler for my Tail object on the "error" event allows my application to cleanly handle this scenario without crashing. Is there another way for the application to catch this exception?

lucagrulla commented 3 years ago

you app should handle the exception on its side:

try {

 tail = new Tail("fileToTail");
 tail.on("line", function(data) {
  console.log(data);
});

tail.on("error", function(error) {
  console.log('ERROR: ', error);
});
} catch (ex) {
 //check for file to come back first
// create a new instance of tail on the newly created file
}
andrewnguyen92 commented 3 years ago

Hey Luca,

I've tried that previously but it's unable to catch the exception. I've tried it again and this is what I get when the file is deleted and the application crashes:

ERROR:  size check for ./file.log failed: Error: ENOENT: no such file or directory, stat './file.log'
/home/user/test/node_modules/tail/lib/tail.js:78
            throw err;
            ^

Error: ENOENT: no such file or directory, stat './file.log'
    at Object.fs.statSync (fs.js:948:11)
    at Tail.latestPosition (/home/user/test/node_modules/tail/lib/tail.js:74:23)
    at Tail.change (/home/user/test/node_modules/tail/lib/tail.js:118:22)
    at Tail.watchEvent (/home/user/test/node_modules/tail/lib/tail.js:183:18)
    at FSWatcher.watcher.fs.watch (/home/user/test/node_modules/tail/lib/tail.js:143:101)
    at emitTwo (events.js:126:13)
    at FSWatcher.emit (events.js:214:7)
    at FSEvent.FSWatcher._handle.onchange (fs.js:1364:12)

Looks like the function throwing the exception is called as a callback by fs.watch, so I don't believe there's a way to catch the exception in that case.

lucagrulla commented 3 years ago

tracked with issues #129 Will be fixed with v2.2.1. Tail will emit an error event if a file is deleted.