【发布时间】:2020-01-02 05:43:53
【问题描述】:
我正在编写一个带有事务回滚的简单 json 数据库。 我需要将一行文本附加到文件中,然后根据我的附加是否成功将成功或失败记录到另一个文件中。如果需要,第二个文件用于回滚。所以在继续之前我需要确定写入是否成功。
我正在使用 stream.write 附加我的文本行,其中包含一个回调,该回调应该验证写入操作的成功或失败。
然后我在以下 URL 的 NodeJS 文档中读到了这个不幸的消息 https://nodejs.org/api/stream.html#stream_class_stream_writable
writable.write() 方法将一些数据写入流,并调用 完全处理数据后提供的回调。如果 发生错误时,回调可能会或可能不会被错误调用为 它的第一个论点。要可靠地检测写入错误,请添加侦听器 对于“错误”事件。
因此,虽然以下代码似乎有效,但文档说它不可靠。
// 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.
文档说要添加这样的侦听器,但我的问题是它不是回调的一部分
// 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.
我找不到任何显示如何执行此操作的示例代码。 所以我想我的问题是: 我可以以某种方式将 on 错误侦听器写入回调,还是有其他方法可以回调写入是否成功?
谢谢,约翰
【问题讨论】:
-
你使用的是什么版本的节点?
-
我使用的是 10.15.3 但我正在阅读最新的文档。
标签: node.js