javascriptreact-nativenpmexpobuffer

Buffer is not defined (react-native)


I can't use buffer in react-native app (built with the expo tool).

I have a geography Point value in hex like this for example -> 0101000020E61000003868AF3E1E0A494046B3B27DC8F73640 and im trying to decode it to longitude and latitude with the following code ->

import WktParser from 'terraformer-wkt-parser';
import wkx from 'wkx';
import wellknown from 'wellknown';
import { Buffer } from 'buffer';

  const wkb = new Buffer.from(point, 'hex');
  const wkt = wkx.Geometry.parse(wkb).toWkt();
  const parsedPoint = WktParser.parse(wellknown.stringify(wkt));
  const longitude = parseFloat(parsedPoint.coordinates[0]);
  const latitude = parseFloat(parsedPoint.coordinates[1]);

  return [latitude, longitude];

but got an error with a buffer like this -> ReferenceError: Can't find variable: Buffer In package.json I have ->

    "terraformer-wkt-parser": "^1.2.1",
    "util": "^0.12.5",
    "wellknown": "^0.5.0",
    "wkx": "^0.5.0"
    "buffer": "^6.0.3",
    "expo": "~47.0.12",

Also, I was trying other libraries and had the same result. Thanks in advance for your help 🙂


Solution

  • To use the buffer module in Expo, you must install it using the expo install buffer command.

    However, since Expo does not support buffer modules by default, executing the expo install buffer command may result in errors such as "Package 'buffer' is not found in the current configured register".

    In this case, you can use the Buffer API by installing the react-native-crypto package instead.

    However, because the react-native-crypto is not supported by Expo, you may need to use bare workflow by ejecting Expo.

    EDIT

    My answer is not about buffer, I write additional answers to @matek comment questions.

    you can use base64 encoding

    import { encode, decode } from 'base-64';
    
    // Encoding coordinate values
    const lat = 37.7749;
    const lng = -122.4194;
    const encodedLatLng = encode(`${lat},${lng}`);
    
    // Decode encoded coordinate values
    const decodedLatLng = decode(encodedLatLng).split(',');
    const decodedLat = parseFloat(decodedLatLng[0]);
    const decodedLng = parseFloat(decodedLatLng[1]);