简体   繁体   English

节点js-将数据写入可写流

[英]Node js- writing data to the writable stream

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. 每次写完成时我都需要调用其他方法。我怎么能这样做。

From the node.js WritableStream.write(...) documentation you can give the "write" method a callback that is called when the written data is flushed: 从node.js WritableStream.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,您仍然可以调用后续写入,并且节点会将挂起的写入请求缓冲到内存中。

I am using maerics's answer along with error handling. 我正在使用maerics的答案以及错误处理。 The flag 'a' is used to Open file for appending. 标志'a'用于打开文件以进行追加。 The file is created if it does not exist. 如果文件不存在,则创建该文件。 There Other flags you can use. 你可以使用其他标志

// 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM