With the writeToFile function it is possible to write strings to a file.
For security reasons the file can only be located on a connected USB stick or on a dedicated
folder of the device. If the filePath provided is not on the connected USB stick, the file is
automatically created in the device's dedicated directory (on the device this is usually in
"/opt/user_files/", on the windows simulation this directory is in the designer's install path
(pclient/user_files/). Note that a file is automatically created if it does not exist yet (this will fail
if the path contains directories that do not exist).
Alternatively, the user_files directory can be created using the createUSBDirectory
function.
If the file is located on a USB stick, the size of the file is not restricted (write will fail if there is
no space left on the device). If the file is located on the file system of the device, the memory
that is available in the /opt/user_files directory is limited to 100 MB (you can create many
smaller files but not more than 100 MB in the directory). Writing will fail if this limit is reached.
From this version onwards, files can also be saved in the directory /opt/data. This folder will
be backed up during an OS / application update, which is advantageous to keep data intact
(only for i.MX6 devices).
The stringToWrite parameter may contain any string. No line breaks are added at the end of
each write, these need to be added to the stringToWrite if desired (add "\n" for a line break). If
the string only consists of one line, a line break has to be added at the end.
The option parameter can either be "append" or "replace". If the string is appended, the
string will just be added at the end of the file. If the string is replaced, the whole content of the
file is discarded before writing the new string to the file. If any other string is provided as
option parameter the writeToFile function will fail.
The optional sync parameter can be set to true if the file shall be directly written to disk
(reduce the risk of corrupt files at total power loss). The sync to disk will be done after the
content was written to the file. If the sync parameter is set to true the writeToFile function will
not return until synchronization is finished! If the sync parameter is omitted or set to false,
the synchronization will be done by the operating system after some time or when the device
is shut down.
The return value of the writeToFile function is either true if writing to the file (and optional
sanchronization) was successful or false if writing or synchronizing to disk failed.
Prototype:
var result = writeToFile(string filePath, string stringToWrite,
string option, bool sync);
Example:
var usbMountPath = getVariableValue("@USBMountPath");
var filePath = usbMountPath + "/myFile.txt";
var myTextWithLineBreak = "Hello, this is line 1.\nAndThis is
line 2.\n";
var doSync = false;