Buffer and stream modules in Node. js details _ node. js-js tutorial

Source: Internet
Author: User
This article mainly introduces Node. the buffer and stream modules in js are described in detail. This article describes the Buffer modules, classes: buffer, write Buffer, copy buffer, and stream module. For more information, see Buffer module

Js was originally designed for browsers, so it can handle unicode encoded strings well, but cannot process binary data well. This is a problem with Node. js, because Node. js is designed to send and receive data that is often transmitted in binary format on the network. For example:

-Send and receive data over TCP connections;
-Read Binary data from images or compressed files;
-Read and Write Data from the file system;
-Process binary data streams from networks

The Buffer module provides a method for storing raw data for Node. js, so binary data can be used in the context of js. The Buffer module may be used whenever you need to process data in the I/O operation in Node. js.

Class: Buffer

The Buffer class is a global variable type used to directly process binary data. It can be built in multiple ways.

The raw data is stored in the Buffer class instance. A Buffer instance is similar to an integer array.

1. new Buffer (size): allocate a new buffer with eight bytes of size.
2. new Buffer (array): allocates a new buffer using an 8-byte array.
3. new Buffer (str, [encoding]): encoding String type-encoding method used. Optional.

4. Class Method: Buffer. isEncoding (encoding): If the given encoding is valid, true is returned; otherwise, false is returned.
5. Class Method: Buffer. isBuffer (obj): test whether the obj is a Buffer. Return a Boolean value.
6. Class Method: Buffer. concat (list, [totalLength]): list {Array} Array type, Buffer Array, used for connection. Total size of all buffers in the preceding Buffer array of totalLength {Number} type.
In addition to the Buffer entity that can be read from the file, it can also be directly constructed, for example:

The Code is as follows:


Var bin = new Buffer ([0x48, 0x65, 0x6c, 0x6c, 0x6c]);

Buffer is similar to a string. In addition to the. length attribute, you can use the [index] method to read the bytes at the specified position. For example:

The Code is as follows:


Bin [0]; // => 0x48;


Buffer and string can be converted to each other. For example, you can use the specified encoding to convert binary data to a string:

The Code is as follows:


Var str = bin. toString ('utf-8'); // => "hello"


The. slice method does not return a new Buffer, but returns a pointer to a position in the middle of the original Buffer, as shown below.

The Code is as follows:


1. [0x48, 0x65, 0x6c, 0x6c, 0x6c]
2. ^
3. |
4. bin. slice (2)

Write Buffer

The Code is as follows:


Var buffer = new Buffer (8); // create a buffer allocated with 8 bytes of memory
Console. log (buffer. write ('A', 'utf8'); // output 1


This will write the character "a" into the buffer. node returns the number of bytes written into the buffer after encoding. The UTF-8 encoding of the letter a here occupies 1 byte.

Copy Buffer

Node. js provides a method to copy the overall content of a Buffer object to another Buffer object. We can only copy existing Buffer objects, so we must create them.

The Code is as follows:


Buffer. copy (bufferToCopyTo)

BufferToCopyTo is the target Buffer object to be copied. Example:

The Code is as follows:


Var buffer1 = new Buffer (8 );
Buffer1.write ('nice to meet U', 'utf8 ');
Var buffer2 = new Buffer (8 );
Buffer1.copy (buffer2 );
Console. log (buffer2.toString (); // nice to meet u

Stream module

In UNIX operating systems, stream is a standard concept. There are three major streams:

1. Standard Input
2. standard output
3. Standard Error

Readable stream

If the buffer zone is the method by which Node. js processes the raw data, it is often the method by which Node. js moves data. The stream in Node. js is readable or writable. Many modules in Node. js use streams, including HTTP and file systems.

Suppose we create a classmates.txt file and read the name list from it to use the data. Since the data is a stream, this means that before reading the file, you can perform data operations starting from the first few bytes received. This is a common mode in Node. js:

The Code is as follows:


Var fs = require ('fs ');
Var stream = fs.ReadStream('classmates.txt ');
Stream. setEncoding ('utf8 ');
Stream. on ('data', function (chunk ){
Console. log ('read some data ')
});
Stream. on ('close', function (){
Console. log ('all the data is read ')
});

In the preceding example, event data is triggered when new data is received. The close event is triggered after the file is read.

Writable stream

Obviously, we can also create writable streams to write data. This means that as long as a simple script, you can use the stream to read the file and write it to another file:

The Code is as follows:


Var fs = require ('fs ');
Var readableStream = fs.ReadStream('classmates.txt ');
Var writableStream = fs.writeStream('names.txt ');
ReadableStream. setEncoding ('utf8 ');
ReadableStream. on ('data', function (chunk ){
WritableStream. write (chunk );
});
ReadableStream. on ('close', function (){
WritableStream. end ();
});

Now, when a data event is received, the data is written to a writable stream.

Readable. setEncoding (encoding): Return: this

Readable. resume (): Same as above. This method allows the readable stream to continue to trigger data events.

Readable. pause (): Same as above. This method causes a stream in the flow mode to stop triggering the data event, switch to the non-flow mode, and leave the available data in the internal buffer zone.
Class: stream. Writable

The Writable (Writable) Stream interface is an abstraction of the data you are writing to a target.

1. writable. write (chunk, [encoding], [callback]):

Chunk {String | Buffer} data to be written
Encoding {String} encoding, if chunk is a String
Callback {Function} callback after data block writing
Return Value: {Boolean} true if all data has been processed.

This method writes data to the underlying system and calls the callback after the data is processed.

2. writable. cork (): forcibly stranded all writes.

Stranded data will be written when. uncork () or. end () is called.

3. writable. end ([chunk], [encoding], [callback])

Chunk {String | Buffer} (optional) data to be written
Encoding {String} encoding, if chunk is a String
Callback {Function} (optional) callback after the stream ends
Calling write () after end () produces an error.

The Code is as follows:


// Write 'hello, 'and use 'World! 'End
Http. createServer (function (req, res ){
Res. write ('hello ,');
Res. end ('World! ');
// Writing is not allowed now
});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.