Here is an example (works on playground) of reading and writing a file in Tabris. (this may be a good snippet to aid in understanding of “paths” on iOS/Android/Windows)
If you try to read the file which doesn’t exist a general error is reported back.
How to I test to see if a file exists?
I’ve tried some Nodejs methods that didn’t work.
Thanks
CODE
const {fs, Button, TextView, TextInput, ui} = require('tabris')
const FILENAME = 'hello.txt'
const FILEPATH = fs.filesDir + '/' + FILENAME
console.log(FILEPATH)
let btnReadFile = new Button({
centerX: 0, top: 'prev() 10', width: 200,
text: 'Read File: ' + FILENAME
}).appendTo(ui.contentView)
btnReadFile.on('select', () => {
fs.readFile(FILEPATH, 'utf-8')
.then(text => txiFile.text = text)
.catch(err => console.error(err))
})
let btnWriteFile = new Button({
centerX: 0, top: 'prev() 10', width: 200,
text: 'Write File: ' + FILENAME
}).appendTo(ui.contentView)
let btnRemoveFile = new Button({
centerX: 0, top: 'prev() 10', width: 200,
text: 'Remove File: ' + FILENAME
}).appendTo(ui.contentView)
btnWriteFile.on('select', () => {
fs.writeFile(FILEPATH, txiFile.text, 'utf-8')
.then(() => console.log('file written:', FILEPATH))
.catch(err => console.error(err))
})
btnRemoveFile.on('select', () => {
txiFile.text = ''
fs.removeFile(FILEPATH)
.then(() => console.log('file removed:', FILEPATH))
.catch(err => console.error(err))
})
let txiFile = new TextInput({
top: 'prev() 20', left: '20%', right: '20%', height: 100,
type: 'multiline'
}).appendTo(ui.contentView)
Updated code with fs.readDir solution NOT working...
function always returns false
- yet inside async function()
I see it is working, and filesDir lists file correctly.
const FILENAME = 'helloxxppp.txt'
const FILEPATH = fs.filesDir
const FULLFILEPATH = FILEPATH + '/' + FILENAME
console.log('FILENAME: \n ' + FILENAME)
console.log('FILEPATH: \n ' + FILEPATH)
console.log('FULLFILEPATH \n: ' + FULLFILEPATH)
// this ALWAYS is false
if (fileExist(FILEPATH, FILENAME)) {
console.log('File NOT exists\n')
} else {
console.log('File exists\n')
}
async function fileExist (path, file) {
let files
try {
files = await fs.readDir(path)
console.log(files)
} catch (err) {
return false
}
return files.indexOf(file) > -1
}