Cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

file exist detection

ANSWERED

Hi, is there any protection on file reading?

The app will be hanged if file is not exist.

    let utf8_read = fs.readFileSync("test.txt", "utf-8");

    ...

    Unhandled Error

    Couldn't find file: test.txt

 

the file state is not protected too:

    let stats = fs.statSync("test.txt");
    if (stats) {...}

    ...

   Unhandled Error

   Couldn't stat file:test.txt

Best Answer
0 Votes
1 BEST ANSWER

Accepted Solutions

I got around this by putting the file access in a try-catch block. Not ideal, but works for now until they add support for some sort of API for checking if a file exists.

View best answer in original post

Best Answer
8 REPLIES 8

I got around this by putting the file access in a try-catch block. Not ideal, but works for now until they add support for some sort of API for checking if a file exists.

Best Answer

Thank you skyway!

It works!

 

//check file
console.log("we are to check setting file regardless");
var utf8_read;
try {
utf8_read = fs.readFileSync("mySettings.txt", "utf-8");
} catch(e) {
console.log('Oh snap we have an error: ', e);
fs.writeFileSync("mySettings.txt", "off", "utf-8");
}

Best Answer

Thank you skyway!

It works!

 

//check file
console.log("we are to check setting file regardless");
var utf8_read;
try {
utf8_read = fs.readFileSync("mySettings.txt", "utf-8");
} catch(e) {
console.log('Oh snap we have an error: ', e);
fs.writeFileSync("mySettings.txt", "off", "utf-8");
}

 

 

I am really happy with this error message and will keep it there.
 
 
 
[7:44:00 PM]Oh snap we have an error: app/index.js:238
[7:44:00 PM]Error: Couldn't find file: mySettings.txt
 
 
 
:smiley:
Best Answer
0 Votes

I'm having trouble with this method, my try doesn't seem to catch anything.

 

  try {
    let jsonObject  = fs.readFileSync("save.txt", "json");
    level = jsonObject.level;
  } catch(e) {
    level = 1;
  }

It always says "Unhandled Error: Couldn't find file: save.txt".

 

What have I done wrong?

Best Answer
0 Votes

We are aware of this issue and it will be fixed in a future update. This should not prevent the code from executing.

Best Answer
Heard about it after the firmware upgrade. I am to give it a try soon and
will give feedback here.
Best Answer
0 Votes

Thank you! This helped me solve my issue as well. 

Best Answer
0 Votes

I created a function to test whether a filename exists, which takes the filename as a parameter:

function checkForFile(filename) {
  var dirIter;
  var listDir = fs.listDirSync("/private/data");
  while((dirIter = listDir.next()) && !dirIter.done) {
    if (dirIter.value === filename) {
      return true;
    }
  }
  return false;
}

 

Best Answer
0 Votes