To main page | Opera Unite HowTo'sfile_wrap.js - File WrapperThis is a simple (safe) wrapper for file reading and writing, just like file_get_contents and file_put_contents in PHP: file_wrap.js/*
ver. 0.0001alpha
http://unitehowto.com
BSD license
*/
function safe_file_get(fn, otherwise) {
try {
var dir = opera.io.filesystem.mountSystemDirectory('storage');
var txt = '';
stream = dir.open(dir.resolve('/storage/'+fn),
opera.io.filemode.READ);
if (stream) {
var bytes=stream.read( stream.bytesAvailable );
stream.close();
return bytes;
};
return txt;
} catch(err) { // message: FILE_NOT_FOUND_ERR
return otherwise;
};
};
function safe_file_put(fn, txt) {
try {
var dir = opera.io.filesystem.mountSystemDirectory('storage');
var stream = dir.open('/storage/'+fn, opera.io.filemode.WRITE);
stream.write(txt);
stream.close();
return 1;
} catch(err) { // message: FILE_NOT_FOUND_ERR
return 0;
};
};
How to use itvar file_contents = safe_file_get('filename.txt', 'default');
This will read contents of to /storage/filename.txt file.'default' is the default value that will return if file was not found or something went wrong (some error happened). var res = safe_file_put('filename.txt', 'This is great!')
This will write This is great! string to /storage/filename.txtMinimum config.xmlThis requires fileio library, so:<widget>
<widgetname>Test1</widgetname>
<feature name="http://xmlns.opera.com/fileio">
</feature>
<feature name="http://xmlns.opera.com/webserver">
<param name="type" value="service"/>
<param name="servicepath" value="test"/>
</feature>
</widget>
ThanksThanks to Simon Houston for fixing locking. | Last updated
|