Stream is an abstract interface, and there are many objects in Node that implement this interface. For example, the Request object requesting the HTTP server is a Stream and stdout (standard output).
Node.js,stream has four flow types:
Readable-readable operation.
Writable-writable operation.
Duplex-readable writable operation.
Transform-The operation is written to the data and then the result is read.
all Stream objects are instances of Eventemitter . The usual events are:
Data-triggered when there is a read.
End-triggers when there is no more data to read.
Error-triggered when a fault occurs during receive and write.
Finish-triggers when all data has been written to the underlying system.
one, read data from the stream
varFS = require ("FS");vardata ="';//to create a readable streamvarReaderstream = Fs.createreadstream ('Input.txt');//set the encoding to UTF8. Readerstream.setencoding ('UTF8');//Process Stream Events--data, end, and errorReaderstream.on ('Data', function (chunk) {data+=Chunk;}); Readerstream.on ('End', function () {console.log (data);}); Readerstream.on ('Error', function (err) {console.log (err.stack);}); Console.log ("Program Execution Complete");
Result: The program executes, then prints the contents of Input.txt
Second, write stream
varFS = require ("FS");vardata ='Baidu: Www.baidu.com';//Create a stream that can be written to the file Output.txtvarWriterstream = Fs.createwritestream ('output.txt');//writing data using UTF8 encodingWriterstream.write (data,'UTF8');//Mark file Endwriterstream.end ();//Process Stream Events--data, end, and errorWriterstream.on ('Finish', function () {Console.log ("write complete. ");}); Writerstream.on ('Error', function (err) {console.log (err.stack);}); Console.log ("Program Execution Complete");
The result is that the file is created and the data variables are written to the Output.txt file
third, pipeline flow
The pipeline provides a mechanism for outputting a stream to the input stream. Typically we use it to fetch data from one stream and pass it to another stream.
As shown in the picture above, we compare the file to a water-filled bucket, and the water is the contents of the file, we use a pipe (pipe) to connect two barrels to the water from one bucket into another, so that slowly realize the large file copy process.
The following example we read a file content and write the content to another file.
varFS = require ("FS");//Create a readable streamvarReaderstream = Fs.createreadstream ('Input.txt');//Create a writable streamvarWriterstream = Fs.createwritestream ('output.txt');//Pipe Read and write operations//reads the contents of the Input.txt file and writes the contents to the Output.txt file readerstream.pipe(writerstream); Console.log ("Program Execution Complete");
Viewing the contents of the Output.txt file becomes the content of the Input.txt (note: The original content in the output will be fully covered)
four, chain-flow
A chain is a mechanism that flows through the connection output to another stream and creates multiple flow operation chains. Chained streams are typically used for pipeline operations.
Next we are using pipelines and chains to compress and decompress files.
varFS = require ("FS");varZlib = require ('zlib');//compress input.txt files to input.txt.gzFs.createreadstream ('Input.txt'). Pipe (Zlib.creategzip ()). Pipe (Fs.createwritestream ('input.txt.gz')); Console.log ("file compression is complete. ");
After performing the above operation, we can see the Input.txt compressed file input.txt.gz generated in the current directory.
Next, let's unzip the file
varFS = require ("FS");varZlib = require ('zlib');//Unzip the input.txt.gz file to Input.txtFs.createreadstream ('input.txt.gz'). Pipe (Zlib.creategunzip ()). Pipe (Fs.createwritestream ('Inputtest.txt')); Console.log ("file decompression completed. ");
After doing this, we can see that the Inputtest.txt file is generated in the current directory
v. Supplementary Notes
I now have such a demand, I want to write the contents of input into the outinput inside, but the above method is to reset the contents of the document, I just want to add, and keep the original content to do?
There are 2 ways to summarize:
1, there is coverage status, you can set the write to add parameters to solve the inflow
varFS = require ("FS");//Create a readable streamvarReaderstream = Fs.createreadstream ('Input.txt');//Create a writable stream // set a second parameter append varWriterstream = Fs.createwritestream ('output.txt',{'Flags':'a' });//Pipe Read and write operations//reads the contents of the Input.txt file and writes the contents to the Output.txt filereaderstream.pipe (Writerstream); Console.log ("Program Execution Complete");
2, you can create a readable stream of the completed callback function inside the operation, see the code:
Let FS = require ('FS'); Let data="'; let Data2='your little frog is really cute.';//1. Read the stream//to create a readable streamLet Readstream = Fs.createreadstream ("Input.txt");//Set UTF-8 encodingReadstream.setencoding ('UTF8');//Handling Flow EventsReadstream.on ('Data', chunk = + data + =chunk); Readstream.on ('End', () =writes (data)); Readstream.on ("Error", err =Console.log (Err.strck)); Console.log ("Program 1 Execution Complete");//2. Write Stream//to create a writable streamLet writes = DataS ={Let Writestream= Fs.createwritestream ("OutInput.txt"); //writing to a stream using Utf-8Writestream.write (Data2+datas,"UTF8"); //Mark file EndWritestream.end (); //Handling Event StreamsWritestream.on ("Finish", () = Console.log ("Write Complete")); Writestream.on ("Error", err =Console.log (err.stack)); Console.log ("Program 2 Execution Complete");}
Node.js:Stream (Stream)