Node js - write data to a recorded stream

In my node application, I write data to a file using the write method in the createWriteStream method. Now I need to find out if the recording is complete for a particular stream or not. How can I find it.

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 a different method for every time the recording ends. How can i do this.

+4
source share
2 answers

In the node.js WritableStream.write(...)documentation, you can give the write method a callback that is called when the written data is cleared:

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

, , , , . "write" false, , node .

+6

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();
+1

All Articles