Applications must use binary data when dealing with things like TCP streams or file streams. Node.js uses the Buffer class to handle:

Handling file streams

Suppose we already have a text file called test.txt, which we read with readFile

const fs = require('fs');
fs.readFile('./test.txt', (err, data) => {
    if (err) throw err;
    console.log(data);
    console.log(Buffer.isBuffer(data));
})
Copy the code

If we print data directly, we can see that the console output is similar to <Buffer 2f 2f 20 4e 6f… >, use buffer.isbuffer () to check whether data inherits from the Buffer class, and the result is true

Dealing with the TCP flow

const https = require('https');
const url = 'https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-assets/v3/static/img/frontend.1dae74a.png~tplv-t2oaga2asx-image.imag e';
https.get(url, res => {
    var buf = [];
    res.on('data', (chunk) => {
        console.log(Buffer.isBuffer(chunk));
        console.log(chunk);
        buf.push(Buffer.from(chunk));
    })
    res.on('end', () => {
        fs.writeFileSync('./demo.png', Buffer.concat(buf)); })})Copy the code

We use HTTPS. Get to request an image address, listen for the data event in the callback function, and we can see that buffer.isbuffer (chunk) outputs true each time.

What other interesting things can we do with Buffer besides dealing with the above two cases?

Let’s take a look at the concept of data URLs

Data URLs, URLs prefixed with the Data: protocol, allow content creators to embed small files into documents. Data URLs are made up of four parts: a prefix (Data :), a MIME type indicating the Data type, an optional Base64 tag if non-text, and Data format: Data :[

][;base64],< Data >. Binaries can be rendered as data URIs using Base64 encoding.

Use Data URLs to process image files

const fs = require('fs');
var mime = 'image/png';
var encoding = 'base64';
var uri = 'data:' + mime + '; ' + encoding + ', ';
var data = fs.readFileSync('./demo.png').toString(encoding);
var uri = 'data:' + '[charset='+mime+'] ' + '; ' + encoding + ', ' + data;
console.log(uri);
Copy the code

You can see that the following string is printed: data:[charset=image/ PNG]; base64,iVBORw0KGgoAAAANSUhEUgAAA8EAAAMhCAIAAABHbiTVAAAACXBIWXMAAAsSAAALEgHS3X78AAAgAElEQVR42uzdfWwc550n+K88S1HDmKwOTEGi6 FG3ZcEicYi7BMmSsIDcRUVZa+E4LOpuZp… FPn/wPiXQKZbxliAgAAAABJRU5ErkJggg==

Does it feel familiar? When we build with WebPack, we often convert small images into Base64 encoding and embed them in HTML, which is what we did above.

Create a new HTML, create an IMG tag, copy the printed content to the SRC attribute of the IMG tag, and open the HTML to see that the image is displayed properly. On the other hand, if we only have an encoded string, how do we convert it to a.png or.jpg image format, as follows:

var uri='data:[charset=image/png]; base64,iVBORw0KGgoAAAANSUhEUgAAA8EAAAMhCAIAAABHbiTVAAAACXBIWXMAAAsSAAALEgHS3X78AAAgAElEQVR42uzdfWwc550n+K88S1HDmKwOTEGi6 FG3ZcEicYi7BMmSsIDcRUVZa+E4LOpuZp... FPn/wPiXQKZbxliAgAAAABJRU5ErkJggg==';
var data = uri.split(', ') [1]; Var buf = Buffer. From (data,'base64');
fs.writeFileSync('./test.png', buf);
Copy the code

Using the buffer. from method, we can specify the encoding format to get the corresponding data stream, and write the stream to the format file