How to check if a 'Storage ' entry exists?

Posted on
  • Running some test and figured out that there are at least two possibilities to check if a file/entry exists

    s = require('Storage');
    file = { name : 'ABC', exist : 0};
    
    // variant I
    if (s.list().find(e => (e == file.name))) {
          file.exist = 1;
          console.log(file.name,"exists");
    } else {
          file.exist = 1;
          console.log(file.name,"is missing ");
    }
    
    // variant II
    if (s.read(file.name)) {
          file.exist = 1;
          console.log(file.name,"exists");
    } else {
          file.exist = 1;
          console.log(file.name,"is missing ");
    }
    

    Are there any pros and cons for those variants?

  • Or a 3rd is s.list(/^filename$/) which would be more efficient than s.list.

    However I'd say s.read(...)!==undefined) is the best. Espruino doesn't actually load the file into memory - it just references it as a string - so it's actually very efficient to just check if it is undefined or not as the file data will never actually even be read.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

How to check if a 'Storage ' entry exists?

Posted by Avatar for MaBe @MaBe

Actions