node.jsfilesystemsfsappendfile

Way To Append To File While Keeping the File Size Constant


I am looking for a way to write the logs from NodeJS to a file. I am using fs.appendFile option. Is there a way to keep adding to the file by keeping the file size constant--for example, if the file exceeds 5 MB and a new line comes in, delete the oldest line to accommodate the new line--sort of like in a rolling basis?


Solution

  • If you are open to use a library for your logging instead of appendfile. You could use winston with the Daily rotate file Transport where you can cap the filesize at 5MB or an amount of days or both.

    I would suggest zipping up the logs and keeping them for a few days/weeks and setting up a cron job or something to delete the old files. If you really want to delete all logs, you could delete on rotate

    transport.on('rotate', function(oldFilename, newFilename) {
        fs.unlinkSync('<log-file-name>')
      });
    

    Normally log rotation is handled by the operating system using something like logrotate