简体   繁体   中英

Why does this node.js Buffer contain random values?

I would like to create a node.js Buffer that contains 'x'throughout.

function createBuffer(buffer_size)
{
    var buf = new Buffer(buffer_size);
    var i;
    for (i=0;i<buffer_size;i++)
    {
        buf.write('x');
    }

    return buf;
}

var testbuf = createBuffer(5);
console.log(testbuf);

The console result is;

<Buffer 78 d3 f6 21 7c>

Why does Buffer contain random values when 'x' is written to the Buffer?

You are writing to default offset ie 0 again and again. you should use

buff.write('x',i); //this will increment the offset

What you are getting is some garbage value on other offsets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM