Delete or replace last character from the end of a file

Hello. I am using a file node to save data that I receive into NR every 5 seconds. The data is in json format so the first thing I do is save "[" in the file, then the data arrives every 5 seconds (from an exec node) and I save a "," after the exec node so that the format is
[message1, message2, message3,

To close this (at the end of every day) I use a function node to check if the date has changed. If the date has changed (a new day has started), I want to end the file with messagex]
My problem is that I have a comma after the previous message.

Is there anyway to replace the last comma with a "]" if the new day has been started? Or to delete the last character of a file?

Thanks in advance.

Send the comma before each message rather than after it, but don't include it the first time, send the [ instead.

Unfortunately that won't work because the messages come automatically every 5 seconds from a python script that is executed in the exec node, so I cannot add something before them.

I am testing a solution atm:

When the new date is detected, I use the file node to read the content of my file and output it in msg.payload as a string. After that I use this in a function node:

oldStr = msg.payload
var newStr = oldStr.slice(0, oldStr.length-1);
msg.payload = newStr
return msg

This should return the whole content of my file, minus the last character. Then I use another file node to save the new msg.payload in the same file ("overwrite").

Put a node between the exec and the file write and do it there.

It is probably much safer to append each raw value onto a new line at the end of the file, without any punctuation. Then, when the day is over, read the file into an array, sum the values, and rename or reset the file.