As long as has played nodejs, that must have contacted writable. The res parameter in the request callback parameter of the HTTP module is a writable object. We often write a bunch of things to the top, and finally call the End method? These all belong to writable behavior.
The writable object we created manually is to be used by the user, so both the write and end methods are invoked by the user. As a provider, how do we know what our writable object has been done by the user? Just guess the API, and I'll start by guessing an event. But not! Like readable, it also has to override a method to listen for operations. Here's an example of creating a writable that allows users to write to it and monitor what the user actually wrote (based on Babel-node):
Import stream from ' stream ';
var w = new stream. writable;
W._write = (buffer, enc, next) => {
console.log (buffer + ");
Next (); Trigger "Write complete"
};
W.on (' Finish ', () => {
console.log (' Finish ');
});
void function callee (i) {
if (I <) {
w.write (i + ', ' utf-8 ', () => {
//write Complete
});
{
w.end ();
}
SetTimeout (callee, i + 1);
} (0);
As with readable _read, the above _write throws an exception if it is not overwritten:
Error:not implemented at
Writable._write (_stream_writable.js:430:6) at
Dowrite (_stream_writable.js:301:12 )
In addition, write is designed as an asynchronous method, and the third parameter can be passed in to the completed callback. And the so-called completion is in the implementation function _write, next parameter is called. There is a reason to design write as asynchronous, and if it is performed synchronously, a sequential error may occur when we need to process some asynchronous transactions in the _write method. For example, a disk file write operation is an asynchronous, if we write files ignore this asynchronous, then if the last write operation is blocked not complete, the current write operation may be executed first. So we should make a reasonable call to next in _write, which must be called, otherwise it will fall into wait and cannot continue to write.
Finally, when the data is written, the finish event is triggered, which means that the end method is invoked by the user. If you are doing a file-writing operation, you should close the file at this point.