@@ -222,6 +222,9 @@ export default class TcpSocket {
222222 }
223223
224224 /**
225+ * Sends data on the socket. The second parameter specifies the encoding in the case of a string — it defaults to UTF8 encoding.
226+ *
227+ * The optional callback parameter will be executed when the data is finally written out, which may not be immediately.
225228 *
226229 * @param {string | Buffer | Uint8Array } buffer
227230 * @param {BufferEncoding } [encoding]
@@ -232,18 +235,10 @@ export default class TcpSocket {
232235 if ( this . _state === STATE . DISCONNECTED ) throw new Error ( 'Socket is not connected.' ) ;
233236
234237 callback = callback || ( ( ) => { } ) ;
235- let str ;
236- if ( typeof buffer === 'string' ) str = Buffer . from ( buffer , encoding ) . toString ( 'base64' ) ;
237- else if ( Buffer . isBuffer ( buffer ) ) str = buffer . toString ( 'base64' ) ;
238- else if ( buffer instanceof Uint8Array || Array . isArray ( buffer ) ) str = Buffer . from ( buffer ) ;
239- else
240- throw new TypeError (
241- `Invalid data, chunk must be a string or buffer, not ${ typeof buffer } `
242- ) ;
243-
238+ const generatedBuffer = this . _generateSendBuffer ( buffer , encoding ) ;
244239 Sockets . write (
245240 this . _id ,
246- str ,
241+ generatedBuffer . toString ( 'base64' ) ,
247242 /**
248243 * @param {string } err
249244 */
@@ -255,6 +250,20 @@ export default class TcpSocket {
255250 ) ;
256251 }
257252
253+ /**
254+ * @param {string | Buffer | Uint8Array } buffer
255+ * @param {BufferEncoding } [encoding]
256+ */
257+ _generateSendBuffer ( buffer , encoding ) {
258+ if ( typeof buffer === 'string' ) return Buffer . from ( buffer , encoding ) ;
259+ else if ( Buffer . isBuffer ( buffer ) ) return buffer ;
260+ else if ( buffer instanceof Uint8Array || Array . isArray ( buffer ) ) return Buffer . from ( buffer ) ;
261+ else
262+ throw new TypeError (
263+ `Invalid data, chunk must be a string or buffer, not ${ typeof buffer } `
264+ ) ;
265+ }
266+
258267 /**
259268 * @param {string } address
260269 */
0 commit comments