Search code examples
javascriptreactjsdecodefsfilereader

Library working with Node.js but not on Browser ( FileReader() vs. fs.readFileSync ) Lib: NBT.js


Basically I'm using this NBT parsing library to parse .nbt files into the readable decoded data structures.

var fs = require('fs'),
    nbt = require('nbt');

var data = fs.readFileSync('z,nbt');
nbt.parse(data, function(error, data) {
    if (error) { throw error; }

    console.log(data.value); //This works, prints out my minecraft nbt array structure
});

When I view the file ("z.nbt") in Notepad++ it looks like Binary string: npp

It works perfect on NPM, I get the data structures i'm looking for (Using code above)

However...

Now I'm trying it on web using react.. REACT is calling the nbt.js's parse function, however the parser doesn't work on the browser's file input. (Seems to cause some kind of Logic error, undefined index)

here is the ui

Console error

I'm thinking that FileReader()'s readAsBinaryString method & fs.readFileSync method have different output strings, and NBT.js favors the fs.readFileSync, however I've tried the readAsText(), readAsDataURL(), etc... methods from FileReader and NBT.js can't parse any of these outputs.

My React code for this:

import React from 'react';
import {Container} from "react-bootstrap";
import NavbarToggle from 'react-bootstrap/esm/NavbarToggle';
import nbt from '../nbt';

const Upload = () => {

    // handleUpload = (event) => {
    //     console.log('Success!');
    // }


    
    function handleChange(event) {
        console.log(event.target.files);
        // console.log(event.target.files[0]); //file struc
        const file = event.target.files[0];
        var reader = new FileReader();
        reader.onload = (e) => {

            console.log(e.target.result);


            var x = nbt.parse(e.target.result, function(error, data) {
              if (error) { throw error; }
          
              console.log(data);
          });

        }
        reader.readAsBinaryString(file);
    }


  return (
    <Container>
    Input NBT file <br/>
    <input type="file" onChange={handleChange}></input>
    </Container>
  )
}

export default Upload

This is the nbt.js file i'm importing in react : nbt.js


Solution

  • reader.readAsBinaryString(file); Replace this with read.readAsArrayBuffer(file);