Search code examples
javascriptuploadp5.js

How can I read a text file with a custom extension using p5js


I want to load text files of a custom extension from disk using p5js, preferably with createFileInput(). I can save a text file of a given custom extension using createWriter(), which I can then access and read with no problems on my default notepad. The problem I'm facing occurs when trying to load said text file using createFileInput(), which leads to a file of .type "" instead of the desired "text". For example,

function setup() {
  load = createFileInput(loadFile)
  noCanvas();
  let content = 'Hello World';
  let writer = createWriter('saveFile.ctxt');
  writer.write([content]);
  writer.close();
}

function loadFile(file) {
  console.log(file.type, file.data);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>

Outputs "" data:application/octet-stream;base64,SGVsbG8gV29ybGQ= when loading saveFile.ctxt, which I can't comprehend at all.

Desired output is "text" Hello World, regardless of the custom file extension used.


Solution

  • You can use a FileReader and the FileReader.readAsText() method, taking care to pass file.file from the p5.js callback into it.

    file.file is the "underlying File object. All normal File methods can be called on this".

    let fileInput;
    
    function setup() {
      noCanvas();
      noLoop();
    
      // Used to create the file:
      // (probably won't work in Stack Snippet)
      //const writer = createWriter("saveFile.ctxt");
      //writer.write(["Hello World"]);
      //writer.close();
    
      fileInput = createFileInput(file => {
        const reader = new FileReader();
        reader.onload = e => {
          console.log(e.target.result); // => Hello World
        };
        reader.readAsText(file.file);
      });
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>

    If you were to pass a .txt file to the input, file.data will have the result text already, without the need for the FileReader.