这是在Tabris中读写文件的示例(在操场上工作)。 (这可能是一个很好的摘要,有助于理解iOS / Android / Windows上的“路径”)
如果您尝试读取不存在的文件,则会报告一般错误。
如何测试文件是否存在?
我尝试了一些无效的Node.js方法。
谢谢
代码
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)
函数总是返回false
-但是在async function()
内部,我看到它正在工作,并且filesDir正确列出了文件。
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
}
答案 0 :(得分:1)
异步/等待版本:
const {fs} = require('tabris')
async function fileExist(path, file) {
let files
try {
files = await fs.readDir(path)
} catch (err) {
return false
}
return files.indexOf(file) > -1
}
承诺版本:
const {fs} = require('tabris')
function fileExist(path, file) {
return new Promise((resolve, reject) => {
fs.readDir(path)
.then(files => resolve(files.indexOf(file) > -1))
.catch(err => resolve(false)) // Error is ignored intentionally
})
}
用法:
1)使用then
:
const FILENAME = 'helloxxppp.txt'
const FILEPATH = fs.filesDir
fileExist(FILEPATH, FILENAME).then((exist) => {
if (exist) {
console.log('File NOT exists\n')
} else {
console.log('File exists\n')
}
})
2)使用async/await
:
async myFunction() {
// code here
let exist = await fileExist(FILEPATH, FILENAME)
if (exist) {
console.log('File NOT exists\n')
} else {
console.log('File exists\n')
}
}