diff --git a/index.js b/index.js index 1a96b6c..ebea290 100644 --- a/index.js +++ b/index.js @@ -1,5 +1,6 @@ var debug = require('debug')('node-crc16'); var crc16Native = require('./build/Release/crc16.node'); +var util = require('./util/util'); var parseParam = function (input, encoding, option) { encoding = encoding || 'hex'; @@ -13,15 +14,7 @@ var parseParam = function (input, encoding, option) { var buf = (function () { if (typeof input === 'string') { try { - /* - * Buffer.from is added in v5.10.0, as the api document shows. But some node version, - * v4.2.6 for example, Buffer.from is function, however, there is an error when you call - * `Buffer.from(string, encoding)`(error some like `hex is not function`). - * */ - if (typeof Buffer.from === 'function' && process.version >= "v5.10.0") { - return Buffer.from(input, encoding); - } - return new Buffer(input, encoding); + return util.bufferFactory(input, encoding); } catch (e) { console.trace(e); debug(e); diff --git a/package-lock.json b/package-lock.json index bf1a5fc..dceb74e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "node-crc16", - "version": "1.0.0-alpha", + "version": "1.0.0-alpha.1", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/test/test.syntax.js b/test/test.syntax.js index 21f57a6..33ede93 100644 --- a/test/test.syntax.js +++ b/test/test.syntax.js @@ -1,5 +1,6 @@ var should = require('chai').should(); var crc16 = require('../index'); +var util = require('./../util/util'); var stream = '3a16070a00000000001a0000'; var sumShouldStr = '98af'; @@ -20,7 +21,7 @@ describe('Syntax to call the apis', function(){ sum.should.eql(sumShouldArry); }) it('Stream input can be a buffer', function(){ - var sum = crc16.checkSum(Buffer.from(stream, 'hex')); + var sum = crc16.checkSum(util.bufferFactory(stream, 'hex')); sum.should.equal(sumShouldStr); }) }) @@ -35,7 +36,7 @@ describe('Syntax to call the apis', function(){ isValid.should.equal(true); }) it('Stream input can be a buffer', function(){ - var isValid = crc16.verifySum(Buffer.from(stream + sumShouldStr, 'hex')); + var isValid = crc16.verifySum(util.bufferFactory(stream + sumShouldStr, 'hex')); isValid.should.equal(true); }) }) diff --git a/util/util.js b/util/util.js new file mode 100644 index 0000000..f577056 --- /dev/null +++ b/util/util.js @@ -0,0 +1,14 @@ +module.exports.bufferFactory = function(){ + var args = Array.prototype.slice.call(arguments, 0); + /* + * Buffer.from is added in v5.10.0, as the api document shows. But some node version, + * v4.2.6 for example, Buffer.from is function, however, there is an error when you call + * `Buffer.from(string, encoding)`(error some like `hex is not function`). + * */ + if (typeof Buffer.from === 'function' && process.version >= "v5.10.0") { + return Buffer.from.apply(null, args); + } + + args.unshift(null); + return new (Function.prototype.bind.apply(Buffer, args)); +}