Node js-将数据写入可写流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19051510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:47:03  来源:igfitidea点击:

Node js- writing data to the writable stream

node.jsstream

提问by sachin

In my node application im writing data to the file using write method in the createWriteStream method.Now i need to find whether the write for the particular stream is complete or not.How can i find that.

在我的节点应用程序中,我使用 createWriteStream 方法中的 write 方法将数据写入文件。现在我需要找到特定流的写入是否完成。我怎么能找到。

var stream = fs.createWriteStream('myFile.txt', {flags: 'a'});
var result = stream.write(data);

writeToStream();
function writeToStream() {
  var result = stream.write(data + '\n');
  if (!result) {
    stream.once('drain',writeToStream());
  }
}

I need to call other method for every time when write completes.How can i do this.

每次写入完成时,我都需要调用其他方法。我该怎么做。

采纳答案by maerics

From the node.js WritableStream.write(...)documentationyou can give the "write" method a callback that is called when the written data is flushed:

从 node.jsWritableStream.write(...)文档中,您可以为“write”方法提供一个回调,在刷新写入的数据时调用该回调:

var stream = fs.createWriteStream('myFile.txt', {flags: 'a'});
var data = "Hello, World!\n";
stream.write(data, function() {
  // Now the data has been written.
});

Note that you probably don't need to actually wait for each call to "write" to complete before queueing the next call. Even if the "write" method returns false you can still call subsequent writes and node will buffer the pending write requests into memory.

请注意,在将下一个调用排队之前,您可能实际上不需要等待每个“写入”调用完成。即使“write”方法返回false,您仍然可以调用后续写入,节点会将挂起的写入请求缓冲到内存中。

回答by Hitesh Sahu

I am using maerics's answer along with error handling. The flag 'a'is used to Open file for appending. The file is created if it does not exist. There Other flagsyou can use.

我正在使用 maerics 的答案以及错误处理。该标志'a'用于打开文件进行追加。如果文件不存在,则创建该文件。您可以使用其他标志

// Create a writable stream &  Write the data to stream with encoding to be utf8
    var writerStream = fs.createWriteStream('MockData/output.txt',{flags: 'a'})
                         .on('finish', function() {
                              console.log("Write Finish.");
                          })
                         .on('error', function(err){
                             console.log(err.stack);
                          });


    writerStream.write(outPutData,function() {
      // Now the data has been written.
        console.log("Write completed.");
    });

    // Mark the end of file
    writerStream.end();