I am writing a simple json database with transaction rollbacks. I need to append a line of text to a file and then log success or failure to another file depending on if my append was successful or not. The second file is used for rollbacks if required. So I need to know for sure that the write was successful before proceeding.
I am using stream.write to append my line of text which includes a callback that is supposed to verify success or failure of the write operation.
Then I read this unfortunate news in the NodeJS docs at the following URL https://nodejs.org/api/stream.html#stream_class_stream_writable
The writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback may or may not be called with the error as its first argument. To reliably detect write errors, add a listener for the 'error' event.
So while the following code seems to work, the docs say it will not be reliable.
// Wait till the file is open before trying to write to it.
wStream.on('open', function()
{
// Call function to append the string to the file with a new line character added at the end.
wStream.write(stringData + '\n', function(error)
{
if(!error) // If the string was appended successfully:
{
callback(false); // Report back there was no error
}
else // The string was not appended successfully.
{
lib.log
(
'h0fceuftq8xkdkvh4dl9' + '\n' +
'Error appending to file ' + fileName + '\n' +
'This was the error:' + '\n' +
JSON.stringify(error) + '\n' +
'\n'
);
callback('Error appending to file ' + fileName)
} // End of: else The string was not appended successfully.
}); //End of: wStream.write(...
// End of: Call function to append the string to the file with a new line character added at the end.
}); // End of: wStream.on('open', function(){Do stuff}
// End of: Wait till the file is open before trying to write to it.
The docs say to add a listener like this but my problem is that it is not part of the callback
// Listen for errors on the write stream and log them.
wStream.on('error', function(error)
{
lib.log
(
'pmazz7shsko8mfnc0gyz' + '\n' +
'An error occured when appending to ' + fileName + '\n' +
'This was the error:' + '\n' +
JSON.stringify(error) + '\n' +
'\n'
);
}); // End of: wStream.on('error', function(error)
// End of: Listen for errors on the write stream and log them.
I have not been able to find any example code which shows how to do this. So I guess my question is: Can I somehow write the on error listener into the callback or is there some other way to callback whether or not the write was successful?
Thanks, John