zoukankan      html  css  js  c++  java
  • [Node.js] Node.js Buffers

    >> node
    >>fs.readFile('finnish.txt', function(err,data){
        console.log(data);
    });
    // Output string is not what we want
    
    >>fs.readFile('finnish.txt', function(err, data){
        console.log(data.toString());
    });
    // Ouptu is ok
    
    /* Encoding */
    >>fs.readFile('finnish.txt', 'utf8', function(err,data){
        console.log(data);
    });
    // Ouptu is ok
    
    >>str = 'u0048u0065u006cu006f u0057u006fu0072u006cu0064u0021';
    'Hello World'
    
    str.length
    12
    
    Buffer.byteLength(str, 'utf8')
    12
    
    But the Buffer.byteLength and str.length are not equal!!
    
    ------
    
    >>str = 'u00bd + u00bc = u00be';
    '1/2 + 1/4 = 3/4';
    
    str.length
    9
    
    Buffer.byteLength(str, 'utf8')
    12
    
    
    -----
    
    >>buf = new Buffer(5)
    >>buf.write('hello wolrd');
    >>buf.toString()
    'hello'
    
    >>buf.write('hello', 2);
    hehel
    
    
    >>buf.write('xxxx', 2, 1);
    >>buf.toString()
    hexel
    
    >>buf.write('xxxx', 2, 2);
    >>buf.toString()
    hexxel
    
    >>buf.write('yyyy', 2, 1, 'utf8')
    >>buf.toString()
    heyel
    
    
    -----
    
    buf1 = new Buffer('1234')
    buf2 = new Buffer('0123')
    buf3 = new Buffer('1234')
    
    buf1.compare(buf2)
    1 //not equal
    buf1.compare(buf3)
    0 //equal
    
    buf1.equals(buf2)
    false
    
    
    >>var arr = [buf1, buf2]
    >>arr.sort(Buffer.compare)
    [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
    
    >>buf.toJSON()
    {type: 'Buffer', data: [104, 101, 121, 101, 108]}
    
    
    >>  buf = new Buffer('Hello World!');
    >>  buf2 0 buf.slice(0,3)
    
    buf2.toString();
    'Hel'

    In this lesson, we cover the Node.js Buffer object in detail. Not only will you learn that the buffer object is a reference to a memory space outside of the V8 engine, but you will learn practical methods to access it, modify it, and convert it to standard Javascript objects that can be used by your code. Examples and discussion are provided for using the toString() method, determining the byte length of the buffer, writing to a buffer, how to avoid truncating data, comparing buffers for equality using both compare() and equals(), and copying buffers using slice().

  • 相关阅读:
    Web_0002:关于MongoDB的操作
    JN_0008:win下通过cmd进入指定目录
    H5_0008:链接分享图片和判断平台
    H5_0007:使用base64做为背景图片
    JN_0007:微信昵称设置小数字
    H5_0006:JS判断PC,平板,手机平台的方法
    H5_0002:微信分享设置
    Web_0001:关于阿里云防盗链Referer,CDN加速,OSS自定义域名的操作
    H5_0001:localStorage本地存储
    JN_0006:MongoDB未授权访问漏洞处理
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4584762.html
Copyright © 2011-2022 走看看