神奇的nodejs:Buffer---二进制文件流和TCP流的文件写入和转码读取,以及输出方式

TCP是基于流式传输的

如果对TCP流式传输不太明白的可以先看上面的解释链接

我们此次以nodejs获取到vcenter认证信息里面的session-id为例,上代码:

const https = require('https');
var session_id = '';
const fs = require('fs');

function getsession_id(params) {
    const options = {
        host: '172.17.xx.xxx',
        port: 443,
        path: '/rest/com/vmware/cis/session',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        auth: '[email protected]:xxxx',
        rejectUnauthorized: false
    };
    const req = https.request(options, (res) => {
        //console.log(res.headers['set-cookie'][0]);
        //if (res.headers['set-cookie'][0].indexOf('vmware-api-session-id') > -1) {
        //    console.log(res.headers['set-cookie'][0]);
        //}
        res.on('data', (d) => {
            console.log(d);
            fs.writeFileSync('a.txt', d);
            process.stdout.write(d);
        });
    });

    req.on('error', (e) => {
        console.error(e);
    });
    req.end();
}

console.log(d)的输出的内容如下:

<Buffer 7b 22 76 61 6c 75 65 22 3a 22 35 62 33 66 39 37 36 64 30 66 37 39 30 35 33 31 61 34 35 35 66 32 33 31 30 62 32 63 66 61 39 31 22 7d>

process.stdout.write(d)的输出内容为:

{"value":"5b3f976d0f790531a455f2310b2cfa91"}

文件a.txt的内容为:

直接读取a.txt的文件内容

const session_idsss = fs.readFileSync('a.txt');

输出内容为:

<Buffer 7b 22 76 61 6c 75 65 22 3a 22 39 39 65 36 61 36 64 33 32 33 30 36 30 34 30 35 36 38 66 65 65 31 30 35 37 38 35 37 39 38 65 31 22 7d>

那么为什么针对同一个TCP流,console.log和process.stdout.write()以及文件写入的形式都不一样呢?

从比较浅层的.log()和process.stdout.write()来讲,标准化输出实现了一些编码的转换,而log知识单纯的将所见所得的字节数据流纯天然的打印在控制台上(当然这样理解可能比较浅显)。

console.log()对于这种tcp流控的打印需要如下方式:

console.log(d.toString())能够达到与process.stdout.write(d)的输出效果

那么我们可以通过文件的输入输出来达到这种的流数据的保存和转换如下:

    const session_idsss = fs.readFileSync('a.txt', {
        encoding: 'utf-8',
        flags: 'string'
    });

 

 

这一部分比较深了,希望以后能继续探讨

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章