Skip to content

Commit

Permalink
Add error handling when file is deleted while watching
Browse files Browse the repository at this point in the history
  • Loading branch information
oliveroneill committed Oct 20, 2017
1 parent 1098056 commit eafa169
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 4 deletions.
14 changes: 12 additions & 2 deletions src/tail.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,12 @@ class Tail extends events.EventEmitter
watch: (pos) ->
return if @isWatching
@isWatching = true
stats = fs.statSync(@filename)
try
stats = fs.statSync(@filename)
catch err
@logger.error("watch for #{@filename} failed: #{@err}") if @logger
@emit("error", "watch for #{@filename} failed: #{@err}")
return
@pos = if pos? then pos else stats.size

if @logger
Expand All @@ -59,7 +64,12 @@ class Tail extends events.EventEmitter

watchEvent: (e) ->
if e is 'change'
stats = fs.statSync(@filename)
try
stats = fs.statSync(@filename)
catch err
@logger.error("'change' event for #{@filename}. #{@err}") if @logger
@emit("error", "'change' event for #{@filename}. #{@err}")
return
@pos = stats.size if stats.size < @pos #scenario where texts is not appended but it's actually a w+
if stats.size > @pos
@queue.push({start: @pos, end: stats.size})
Expand Down
2 changes: 1 addition & 1 deletion test/mocha.opts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
--compilers mocha --compilers coffee:coffee-script/register
--compilers mocha --compilers coffee:coffee-script/register --timeout 3000
23 changes: 22 additions & 1 deletion test/tail.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,25 @@ describe 'Tail', ->
for l in lines
fs.writeSync fd, l+'\n'

fs.closeSync fd
fs.closeSync fd

it 'should send error event on deletion of file while watching', (done)->
text = "This is a line\n"

fd = fs.openSync fileToTest, 'w+'

tailedFile = new Tail fileToTest, {fsWatchOptions: {interval:100}, logger: console}

# ensure error gets called when the file is deleted
tailedFile.on 'error', (line) ->
# recreate file so that `afterEach` can cleanup
fd = fs.openSync fileToTest, 'w+'
done()

tailedFile.on 'line', (line) ->
# delete the file
fs.unlinkSync fileToTest

fs.writeSync fd, text

fs.closeSync fd

0 comments on commit eafa169

Please sign in to comment.