Node.js: Finding a file opened with fs.createWriteStream () that gets deleted
Let's 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 prints a message to the console and also adds it to the log file (which it will generate on startup if needed). Everything works fine.
But now, if I delete the file machine.log
while the process is running, it keeps humming but the recording fails anymore because the file is gone. But it looks like the entries are failing, which means I will need to explicitly check for this condition. I searched the Stream docs but didn't seem to find an explicit event that fires when this type of thing occurs. The return value is write()
also not useful.
How can I detect when the file I'm writing is deleted so I can try to open or recreate the file again? This field is CentOS if relevant.
source to share
In fact, the entries don't fail.
When you delete a file that is open in another program, you delete the named reference to that inode file. The open program is still pointing to this inode. He will happily continue to write on it, actually writing to disk. Only now you have no way of looking at it because you removed the named reference to it. (If there were other links, like hard links, you could still!).
So that programs expecting their log files to "disappear" (b / c logrotate
, say) usually maintain a signal (usually SIGHUP
and sometimes SIGUSR1
)) that tells them to close their file, which indicates that it really is gone because now there is no links to it anywhere) and recreate it.
You should also think about this.
source to share