You writing empty string when it should be null. Could you change to actually write null? Its 0xfb length coded int. (Also in the first loop calculating packet length - should be `if (val === null) { length ++; return; }` )