javascript - Cannot Decode Buffer To Print BLE ECSPOS With React Native - Stack Overflow

admin2025-04-04  0

I use React Native to listen for thermal printing request via LAN IP, then I get the Buffer data. But I don't know how to decode it into text to send to Bluetooth Xprinter. Has anyone ever dealt with this case?

I tried with buffer.toString('utf-8'); but got error same in image

buffer.toString('utf-8') got this error

My code handle it

import TcpSocket from 'react-native-tcp-socket';
import RNXprinter from "react-native-esc-pos-xprinter";
import { Buffer } from 'buffer';

const server = TcpSocket.createServer((socket) => {
      // socket.setEncoding('utf8');
      let binaryData = Buffer.alloc(0);
      socket.on('data', async (chunk) => {
        binaryData = Buffer.concat([binaryData, Buffer.from(chunk)]);
      });

      socket.on('error', (error) => {
        console.error('Socket error:', error);
      });

      socket.on('close', () => {
        console.log('Connection closed');
        const msg = binaryData.toString('utf-8');
        console.log('Received closed data:', msg);
        RNXprinter.pushText(msg, 0);

        // Push Cut Paper
        RNXprinter.pushCutPaper();
      });
    });

    server.listen({ port: parseInt(port, 10), host: '0.0.0.0' }, () => {
      console.log(`Server running on ${deviceIp}:${port}`);
      setServerRunning(true);
      Alert.alert('Print Server', `Server started on ${deviceIp}:${port}`);
    });
});
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1743731816a216697.html

最新回复(0)