10-07-2017 10:10 - edited 10-07-2017 10:18
10-07-2017 10:10 - edited 10-07-2017 10:18
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
Answered! Go to the Best Answer.
10-09-2017 23:28
10-09-2017 23:28
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.
10-09-2017 23:28
10-09-2017 23:28
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.
10-12-2017 19:42
10-12-2017 19:42
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");
}
10-12-2017 19:50
10-12-2017 19:50
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");
}
11-09-2017 09:30
11-09-2017 09:30
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?
11-09-2017 09:41
11-09-2017 09:41
We are aware of this issue and it will be fixed in a future update. This should not prevent the code from executing.
11-09-2017 10:31
11-09-2017 10:31
05-12-2019 20:35
05-12-2019 20:35
Thank you! This helped me solve my issue as well.
09-10-2019 13:46
09-10-2019 13:46
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;
}