从缓冲区创建新对象

时间:2018-11-09 13:36:33

标签: javascript node.js

我想构建一个类似于NodeJS中的Buffer对象的对象。

function Header (type) {
    this.type = type;
    this.color = "red";
    this.fromBuffer = function(b)
    {
        console.log(X);
    };
}

var b  = Buffer.alloc(16);
var hd = Header.fromBuffer(b);

此代码根本不起作用。 我想创建一个新的Header对象,该对象从Buffer加载数据。 这怎么可能?

谢谢!

1 个答案:

答案 0 :(得分:1)

如果缓冲区包含JSON数据,则可以执行以下操作:

function Header (type) {
    this.type = type;
    this.color = "red";
    this.fromBuffer = function(b)
    {
        var data = JSON.parse(b.toString());
        this.type = data.type;
        this.color = data.color;
        return this;
    };

  return this;
}

var b  = new Buffer.from(JSON.stringify({type:"1", color: "blue"}));
var hd = new Header().fromBuffer(b);  
console.log(hd);

输出:

Header { type: '1', color: 'blue', fromBuffer: [Function] }

如果缓冲区中只有字符串数据(假设是颜色),则可以调用b.toString()

function Header (type) {
    this.type = type;
    this.color = "red";
    this.fromBuffer = function(b)
    {
        this.color = b.toString();
        return this;
    };

    return this;
}

var b  = new Buffer.from("blue");
var hd = new Header(1).fromBuffer(b);
console.log(hd);
相关问题