Search code examples
javascriptfilereadershapefile

Array different length in console.log at Javascript?


Hellloo, it my first time find this in js i am trying to put every data that is in the file into an array. And when I checked, there was an oddity, namely the odd array length.

this my code

export function convertGISToGeojson(file) {
  if (file) {
    let geojson = [];

    var promise = new Promise(getBuffer(file));

    promise
      .then(function (data) {
        geojson = data;
        console.log(geojson);
      })
      .catch(function (err) {
        console.log("Error: ", err);
      });

    return geojson;
  } else {
    return null;
  }
}

function getBuffer(fileData) {
  return function (resolve) {
    var reader = new FileReader();
    var shapefile = require("shapefile");
    reader.readAsArrayBuffer(fileData);
    reader.onload = function () {
      let geojson = [];
      let result = reader.result;

      shapefile
        .open(result)
        .then((source) =>
          source.read().then(function log(result) {
            if (result.done) return;
            geojson.push(result.value);
            return source.read().then(log);
          })
        )
        .catch((error) => console.error(error.stack));

      resolve(geojson);
    };
  };
}

when i try to console.log(data) that variable, the result like this console my variable But, when i try to console.log(data[0]), the result is undefined

whats wrong with my code?


Solution

  • Your convertGISToGeojson and getBuffer functions doesn't do what you would expect, you're returning an empty array or null, you don't wait for the promise to resolve or resolve too early, use async/await. I wrapped both functions in the demo below:

    function convertGISToGeojson(fileArrayBuffer) {
    
      return new Promise((resolve, reject) => {
    
        var reader = new FileReader();
        //var shapefile = require("shapefile"); // uncomment this
        reader.readAsArrayBuffer(new Blob([fileArrayBuffer], {
          type: "application/octet-stream"
        }))
        reader.onload = function(evt) {
          let result = reader.result;
          shapefile
            .open(result)
            .then((source) =>
              source.read().then(function log(result) {
                return source.read().then(i => resolve(i.value));
              })
            )
            .catch((error) => reject(error.stack));
        };
        reader.onerror = (event) => reject(reader.error);
    
      })
    
    }
    
    
    (async() => {
    
      let file = 'https://cdn.rawgit.com/mbostock/shapefile/master/test/points.shp';
      let fileBuffer = await fetch(file).then(res => res.arrayBuffer());
    
      convertGISToGeojson(fileBuffer)
        .then(info => console.log('info', info))
        .catch(err => console.log('err', err))
    
    })()
    <script src="https://unpkg.com/shapefile@0.6.6/dist/shapefile.js"></script>