---
title: "Buffer in NodeJS 12 and NodeJS 8"
author: "sillycat"
date: "2020-02-25T06:43:51Z"
tags: []
categories: ["企业架构"]
slug: "buffer-in-nodejs-12-and-nodejs-8"
draft: false
lastmod: "2020-02-25T06:43:51Z"
id: 2512594
url: "https://sillycat.iteye.com/blog/2512594"
---

Buffer in NodeJS 12 and NodeJS 8

My Simple Testing codes
> cat index.js 
const size = 'hello'.length;
const AES_BLOCK_SIZE = 8;
const padLength = (size % AES_BLOCK_SIZE);
let encryptText = Buffer.alloc(size + padLength, '0x06', 'hex');
console.log(encryptText);

Version 8
> node --version
v8.14.1

Run it and it works
> node index.js 
<Buffer 00 00 00 00 00 00 00 00 00 00>

Switch to version 12
> node --version
v12.14.1

It failed
> node index.js 
buffer.js:999
      throw new ERR_INVALID_ARG_VALUE('value', value);
      ^
TypeError : The argument 'value' is invalid. Received '0x06'
    at _fill (buffer.js:999:13)
    at Function.alloc (buffer.js:348:12)
    at Object.<anonymous> (/Users/hluo/work/nodejs/buffer/index.js:4:26)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_main_module.js:17:11 {
  code: 'ERR_INVALID_ARG_VALUE'
}

Understand HEX
ASCII: A (65)
Binary: 0100 _ 0001
Hex: 41

Change the script to be
> cat index.js 
const size = 'hello'.length;
const AES_BLOCK_SIZE = 8;
const padLength = (size % AES_BLOCK_SIZE);
let encryptText = Buffer.alloc(size + padLength, 0x06, 'hex');
console.log(encryptText);


> node index.js 
<Buffer 06 06 06 06 06 06 06 06 06 06>

With the help of nodenv, I can easily switch my nodeJS version and check
https://www.iteye.com/blog/sillycat-2512593


References:
https://nodejs.org/docs/latest-v8.x/api/buffer.html#buffer_class_method_buffer_alloc_size_fill_encoding
https://nodejs.org/docs/latest-v12.x/api/buffer.html#buffer_class_method_buffer_alloc_size_fill_encoding
https://www.jianshu.com/p/57c4e8d3f035