Search code examples
node.jsparse-platformparse-server

How to Store a File to Parse Server with fs


I was having trouble with this, though it probably is a rookie issue. I want to store some file at ../images/icon.png as a File object in my database. I had trouble accessing the actual data and storing it properly. The documentation for Parse.File says you can access the data as

1. an Array of byte value Numbers, or 
2. an Object like { base64: "..." } with a base64-encoded String. 
3. a File object selected with a file upload control.

but I couldn't figure out how to actually do this.


Solution

  • What I ended up doing was

    let iconFile = undefined;
      const filePath = path.resolve(__dirname, '..', 'images/icon.png');
    
      fs.readFile(filePath, 'base64', function(err, data) {
        if (err) {
          console.log(err);
        } else {
          iconFile = new Parse.File('icon', {base64: data});
        }
      });
    

    I was getting errors where the path wasn't pointing to the image correctly, so I used node's path (as in require('path') to get it to point correctly.

    This code should work for any file type, as far as I can tell.