This article describes how to use Node as an example. the Writable object in js is Node. the basic knowledge of getting started with js. If you have ever played nodejs, you must have been familiar with Writable. The res parameter in the request callback parameter of the http module is a Writable object. We often write a bunch of things above, and finally call the end method, right? All of these are Writable behaviors.
The Writable object we created manually is handed over to the user, so the write and end methods are called by the user. As a provider, how do we know what operations the user has performed on the Writable object? Let's guess about this API. I will first guess an event. But not! Like Readable, it must overwrite a method to listen for operations. The following is an example of creating a Writable that allows users to write content to it and monitor what the user has written (based on babel-node ):
Import stream from 'stream'; var w = new stream. writable; w. _ write = (buffer, enc, next) => {console. log (buffer + ''); next (); // triggers" Write completed "}; w. on ('finish ', () => {console. log ('finish ') ;}); void function callee (I) {if (I <10) {w. write (I + '', 'utf-8', () =>{// write completed});} else {w. end () ;}settimeout (callee, 10, I + 1) ;}( 0 );
Like Readable's _ read, if the above _ write is not overwritten, an exception will be thrown:
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. In implementation function _ write, the next parameter is called. There is a reason to design write as Asynchronous. If it is executed synchronously, an error in sequence may occur when we need to process some asynchronous transactions in the _ write method. For example, the write operation on a disk file is asynchronous. If we ignore this asynchronous mode, if the previous write operation is blocked, the current write operation may be executed first. Therefore, we should reasonably call next in _ write (it must be called, otherwise it will be waiting and cannot continue writing ).
Finally, the finish event is triggered after data writing is complete, which means that the end method is called by the user. If you write a file, close the file.