dudleycarr / nsqjs

NodeJS client library for NSQ
https://nsqjs.com
MIT License
558 stars 75 forks source link

byteLength function refuse a String object #341

Closed 743v45 closed 3 years ago

743v45 commented 3 years ago

nsqjs: v0.12.1 node: v12.16.3

Example code

const {Writer} = require('nsqjs');
const writer = new Writer('127.0.0.1', 4150);

writer.connect();

writer.on(Writer.READY, () => {
  // Throw Error
  writer.publish('sample_topic', new String('one'));
});

writer.on(Writer.CLOSED, () => {
  console.log('Writer closed');
});

Throw Error

buffer.js:723
    throw new ERR_INVALID_ARG_TYPE(
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The "string" argument must be of type string or an instance of Buffer or ArrayBuffer. Received an instance of String
    at Function.byteLength (buffer.js:723:11)
    at byteLength (/Users/taevas/Code/upyun/sms/node_modules/nsqjs/lib/wire.js:34:38)
    at command (/Users/taevas/Code/upyun/sms/node_modules/nsqjs/lib/wire.js:99:31)
    at Object.pub (/Users/taevas/Code/upyun/sms/node_modules/nsqjs/lib/wire.js:251:10)
    at WriterConnectionState.produceMessages (/Users/taevas/Code/upyun/sms/node_modules/nsqjs/lib/nsqdconnection.js:731:39)
    at EventEmitter.emit (events.js:310:20)
    at WriterConnectionState.NodeState.raise (/Users/taevas/Code/upyun/sms/node_modules/node-state/lib/nodestate.js:99:29)
    at WriterNSQDConnection.produceMessages (/Users/taevas/Code/upyun/sms/node_modules/nsqjs/lib/nsqdconnection.js:884:23)
    at Writer.publish (/Users/taevas/Code/upyun/sms/node_modules/nsqjs/lib/writer.js:138:22)
    at Writer.<anonymous> (/Users/taevas/Code/upyun/sms/a.local.js:8:10) {
  code: 'ERR_INVALID_ARG_TYPE'
}

code position https://github.com/dudleycarr/nsqjs/blob/main/lib/wire.js#L32

function byteLength(msg) {
  if (_.isString(msg)) return Buffer.byteLength(msg)

  return msg.length
}

Buffer.byteLength can't accept a String object.

Before the crash, It is reasonable that _checkMsgsValidity find what is invalid.