Skip to content

Commit 6b0df28

Browse files
committed
Add File Read/Write example, using folder.userData
1 parent fca9a7a commit 6b0df28

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

docs/file-system-access/file-object.md

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -955,3 +955,82 @@ Writes the specified text to the file at the current position, and appends a Lin
955955
#### Returns
956956

957957
Boolean. `true` on success.
958+
959+
---
960+
961+
## File Object Examples
962+
963+
### Read & Write Files
964+
965+
The below example writes text to a file, then reads the contents of that file and presents it as an alert.
966+
967+
Keep in mind that this is just one way to do this. Some host apps may also require a user-specified permissions check before being able to access the local file system.
968+
969+
Note that this stores (and fetches) the file from the user's appdata folder, using the built-in [Folder.userData](../file-system-access/folder-object.md#folderuserdata) shortcut.
970+
971+
```js
972+
/**
973+
* Reads data from a given file in userdata folder
974+
*
975+
* @param {string} filename Filename, with extension
976+
* @return {string} File contents, if file exists
977+
*/
978+
function readUserDataFromFile(filename) {
979+
var userDataFolder = Folder.userData;
980+
981+
var filepath = userDataFolder.fullName + "/" + filename;
982+
var file = new File(filepath);
983+
984+
// Default encoding
985+
file.encoding = "UTF-8";
986+
987+
if (!file.exists) {
988+
throw "Could not find file '" + String(file.fsName);
989+
}
990+
991+
file.open();
992+
var contents = file.read();
993+
file.close();
994+
995+
return contents;
996+
}
997+
998+
/**
999+
* Writes data to a given file in userdata folder
1000+
*
1001+
* @param {string} filename Filename, with extension
1002+
* @param {string} data Data to write
1003+
*/
1004+
function writeUserDataToFile(filename, data) {
1005+
var userDataFolder = Folder.userData;
1006+
1007+
var filepath = userDataFolder.fullName + "/" + filename;
1008+
var file = new File(filepath);
1009+
1010+
// Default encoding
1011+
file.encoding = "UTF-8";
1012+
1013+
// Write file contents
1014+
file.open("w");
1015+
var success = file.write(data);
1016+
file.close();
1017+
1018+
if (!success) {
1019+
throw "Could not write to file '" + String(file.fsName);
1020+
}
1021+
}
1022+
1023+
try {
1024+
var filename = "myFile.txt";
1025+
var contents = "Hello world!";
1026+
1027+
writeUserDataToFile(filename, contents);
1028+
1029+
var readData = readUserDataFromFile(filename);
1030+
1031+
// "Hello world!"
1032+
alert("File Contents: '" + String(readData) + "'");
1033+
} catch (e) {
1034+
alert(e);
1035+
}
1036+
```

0 commit comments

Comments
 (0)