这是在 Tabris 中读取和写入文件的示例(在操场上工作)。 (这可能是一个很好的片段,有助于理解 iOS/Android/Windows 上的“路径”)
如果您尝试读取不存在的文件,则会报告一般错误。
如何测试文件是否存在?
我尝试了一些无效的 Nodejs 方法。
谢谢
代码
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)
使用 fs.readDir 解决方案更新的代码不起作用...
函数总是返回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
}