Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: Detecting a file, opened with fs.createWriteStream(), becoming deleted

Say I have the following Node program, a machine that goes "Ping!":

var machine = require('fs').createWriteStream('machine.log', {
    flags    : 'a',
    encoding : 'utf8',
    mode     : 0644
});

setInterval(function () {
    var message = 'Ping!';
    console.log(message);
    machine.write(message + '\n');
}, 1000);

Every second, it will print a message to the console and also append it to a log file (which it will create at startup if needed). It all works great.

But now, if I delete the machine.log file while the process is running, it will continue humming along happily, but the writes will no longer succeed because the file is gone. But it looks like the writes fail silently, meaning that I would need to explicitly check for this condition. I've searched the Stream docs but can't seem to find an obvious event that is emitted when this type of thing occurs. The return value of write() is also not useful.

How can I detect when a file I'm writing to is deleted, so I can try to reopen or recreate the file? This is a CentOS box, if that's relevant.

like image 859
smitelli Avatar asked Oct 10 '13 16:10

smitelli


1 Answers

The writes actually do not fail.

When you delete a file that is open in another program you are deleting a named link to that file's inode. The program that has it open still points to that inode. It will happily keep writing to it, actually writing to disk. Only now you don't have a way to look it at, because you deleted the named reference to it. (If there were other references, e.g. hard links, you would still be able to!).

That's why programs that expect their log files to "disappear" (b/c of logrotate, say) usually support a signal (usually SIGHUP and sometimes SIGUSR1) that tells them to close their file (at which point it is really gone, because now there are no links to it anywhere) and re-create it.

You should consider something like that as well.

like image 72
Nitzan Shaked Avatar answered Oct 06 '22 01:10

Nitzan Shaked