bytewiser 练习

bytewiser 是 nodeschool.io 出品的nodejs入门练习项目

bytewiser-exercise-1

Write a node program that prints a buffer object containing the string “bytewiser” using console.log.

1
2
3
var str = 'bytewiser';
var buffer = new Buffer(str);
console.log(buffer);

bytewiser-exercise-2

Given an unknown number of bytes passed via process.argv, create a buffer from them and output a hexadecimal encoded representation of the buffer.

1
2
3
4
5
6
7
var array = process.argv.slice(2);
var buffer = new Buffer(array);
console.log(buffer.toString('hex'));
// 官方答案
// var bytes = process.argv.slice(2).map(function(arg) { return parseInt(arg) })
// console.log(new Buffer(bytes).toString('hex'))

阅读全文

NODEJS-Buffer对象

  • 构造一个指定大小的 buffer

      var newBuffer = new Buffer(1024);
      // var len = newBuffer.length;
    
  • 用指定值初始化 buffer 的内容

      // 填充第10字节开始的内容为 1 
      newBuffer.fill(1, 10);
      // 填充第10~20字节的内容为 2 
      newBuffer.fill(2, 10, 20);
    
  • 用数组初始化 buffer 的内容

      // 用数组 [0, 1, 2] 初始化
      var newBuffer = newBuffer([0, 1, 2]) 
    
  • 用字符串初始化 buffer 的内容

      // 用字符串 'xiaolai' 初始化
      var newBuffer = new Buffer('xiaolai');
      // 指定编码, 默认为 utf8,可选 ascii/utf8/utf16le/ucs2/base64/hex 等编码格式
      // var newBuffer = new Buffer('xiaolai', 'utf8');
    

阅读全文