【问题标题】:Can Callback for stream.write Reliably Verify That the Write Has Succeeded?stream.write 的回调能否可靠地验证写入是否成功?
【发布时间】: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


【解决方案1】:

我认为您不需要为每次写入提供回调。如果error事件没有被执行,则意味着你所有的写入都成功了

 writer.on('error', function(error){
    // handle all errors here
 });

您需要调用writer.end('Last string to write') 让流知道这是您的最后一次写入,然后finish 事件将触发,因此您可以说所有写入都已完成。

希望对你有帮助

【讨论】:

  • 嗨 Jasper 您写道: >如果错误事件未执行,则意味着您的所有写入均成功。//// 我阅读它的方式,文档似乎对此不清楚。 >如果发生错误,回调可能会或可能不会以错误作为其第一个参数来调用。要可靠地检测写入错误,请为“错误”事件添加一个侦听器。///
  • 你写道: >你需要调用 writer.end('Last string to write') 让流知道这是你的最后一次写入,然后完成事件将触发,因此你可以说所有写入都已完成.///
  • 我只写了一行。我会从 writer.end 开始吗?如果我想清楚,我必须在回调中有一些东西告诉我在继续之前我的写是成功的。否则我必须启动回滚过程。另外,我认为我不希望在用户注销之前关闭流,因为在用户工作期间他们将多次写入这些文件。我认为这是流的优点之一——你不需要一直打开和关闭它们。谢谢你的帮助。约翰
【解决方案2】:

pipeline 是我要找的。​​p>

文档描述如下:

在流转发错误之间进行管道传输的模块方法 管道完成时清理并提供回调。

我的信息来源如下。 Source1, Source2

此外,Anto Aravinth 在 SkillShare 上的名为“通过示例了解 NodeJS 流”的课程非常有帮助。

以下是将json记录追加到文件的完成函数,它提供了一种可靠的方法来回调追加成功或失败。 (真的是在追加操作的时候有没有出错)。

// Define function to append a string to a file  
// and create the file if it does not exist.  
lib.append = function(dir, fileName, appendObject, callback)
{
  // Convert the data object to a string.
  let stringData = JSON.stringify(appendObject);

  // Create a readable stream.
  const sourceStream = new Readable();

  // Load the readable stream with data.
  sourceStream.push(stringData + '\n');

  // Tell the stream no more data is coming.
  sourceStream.push(null);

  // Create a writable stream and specify the file which will receive the data from the readable stream.
  let destinationStream = fs.createWriteStream(lib.baseDir + dir + '/' + fileName + '.json', {flags : 'a'});


  pipeline
  (
    sourceStream,
    destinationStream,
    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.
      {
        // Write the error to a log file
        lib.log
        (
          'h0fceuftq8xkdkvh4dl9' + '\n' +
          'Error appending to file ' + fileName + '\n' +
          'This was the error:' + '\n' +
          JSON.stringify(error) + '\n' + 
          '\n'
        );

        // This starts the rollback process for all files involved.
        callback
        (
          'h0fceuftq8xkdkvh4dl9' + '\n' +
          'Error appending to file ' + fileName + '\n' +
          'This was the error:' + '\n' +
          JSON.stringify(error) + '\n'
        );        
      }
    }
  );
}; // End of: lib.append = function(...
// End of: Append a string to a file. 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 2021-03-30
    • 2015-05-16
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多