This page details how to use File I/O from a privileged JavaScript worker thread. For other uses of OS.File, please see the corresponding page.
Using OS.File for Workers
To import OS.File in a chrome worker thread, add the following line at the start of your script:
importScripts("resource://gre/modules/osfile.jsm")
Example: Reading the contents of a file as text
The following snippet opens a file "file.txt" and read its contents as a string, using the default encoding (utf-8).
let decoder = new TextDecoder(); // This decoder can be reused for several reads let array = OS.File.read("file.txt"); // Read the complete file as an array let text = decoder.decode(array); // Convert this array to a text
Example: Write a string to a file
The following snippet writes a text "This is some text" to a string "file.txt", using the default encoding (utf-8). It uses an atomic write to ensure that the file is not modified if, for some reason, the write cannot complete (typically because the computer is turned off, the battery runs out or the application is stopped).
let encoder = new TextEncoder(); // This encoder can be reused for several writes let array = encoder.encode("This is some text"); // Convert the text to an array OS.File.writeAtomic("file.txt", array, {tmpPath: "file.txt.tmp"}); // Write the array atomically to "file.txt", using as temporary // buffer "file.txt.tmp".
The following variant does the same thing but will fail if "file.txt" already exists (notice that noOverwrite is set to true):
let encoder = new TextEncoder(); // This encoder can be reused for several writes let array = encoder.encode("This is some text"); // Convert the text to an array OS.File.writeAtomic("file.txt", array, {tmpPath: "file.txt.tmp", // Write the array atomically to "file.txt", using as temporary noOverwrite: true}); // buffer "file.txt.tmp".
Example: Rename a file
The following snippet renames file "oldname.txt" to "newname.txt". Note that this is generally much faster than copying "oldname.txt" to "newname.txt" and then removing "oldname.txt".
OS.File.rename("oldname.txt", "newname.txt");
Example: Copy a file
The following snippet copies file "oldname.txt" to "newname.txt". On most operating systems, this operation is handled directly by the operating system itself, which makes it as fast as possible.
OS.File.copy("oldname.txt", "newname.txt");
Example: Path manipulation
The following snippet obtains the path to file "sessionstore.js", contained in the user's profile directory.
let sessionstore = OS.Path.join(OS.Constants.Path.profileDir, "sessionstore.js"); // Under Linux, this is generally "$HOME/.firefox/Profiles/$PROFILENAME/sessionstore.js" // Under MacOS, this is generally "$HOME/Library/Application Support/Firefox/$PROFILENAME/sessionstore.js" // Under Windows Vista and later, this is generally "C:\Users\%USERNAME%\AppData\Roaming\Mozilla\Firefox\Profiles\%PROFILENAME%" // etc.
Example: Determine if a file is a directory
The following snippet determines if some path represents a file or a directory. The variable "somePath" holds the path of the file. The code checks if it's a directory or not using "isDir". It also fails safely in case the file doesn't exist:
try { let stat = OS.File.stat(somePath); if (stat.isDir) { // The path represents a directory } else { // The path represents a file, not a directory } } catch (ex) { if (ex instanceof OS.File.Error && ex.becauseNoSuchFile) { // The file does not exist } else { throw ex; // Other error } }
Global object OS.File
Method overview
File open(in string path, [optional] in object mode, [optional] in object options); |
object openUnique(in string path, [optional] in object options); Requires Gecko 27.0 |
void copy(in string sourcePath, in string destPath, [optional] in object options); |
bool exists(in string path); |
string getCurrentDirectory(); |
void makeDir(in string path, [optional] in object options); |
void move(in string sourcePath, in string destPath); |
Uint8Array read(in string path, [optional] in object options); |
void remove(in string path); |
void removeEmptyDir(in string path); |
void removeDir(in string path, [optional] in object options); Requires Gecko 27.0 |
void setCurrentDirectory(in string path); |
void setDates(in string path, in Date|number accessDate, in Date|number modificationDate); |
File.Info stat(in string path, [optional] in object options); |
void writeAtomic(in string path, in ArrayView data, in object options); |
Methods
OS.File.open()
Use method OS.File.open()
to open a file.
File open( in string path, [optional] in object mode, [optional] in object options ) throws OS.File.Error
Arguments
-
path
- The full native name of the file to open.
-
mode
Optional -
The opening mode for the file, as an object that may contain a subset of the following fields:
-
read
-
If
true
, the file will be opened for reading. Depending on other fields, it may also be opened for writing. -
write
-
If
true
, the file will be opened for writing. Depending on other fields, it may also be opened for reading.Prior to Gecko 27, unlesscreate
ortruncate
are set or explicitunixFlags
are given, the file will be opened for appending on Unix/Linux. However, the file is not opened for appending on Windows at the time of writing. See bug 924858. Starting with Gecko 27, you may use theappend
flag instead. -
trunc | truncate
-
If
true
, the file will be opened for writing. If the file does not exist, it will be created. If the file exists, its contents will be removed. Cannot be used withcreate
. -
create
-
If
true
, file will be opened for writing. The file must not exist. If the file already exists, an error is thrown. Cannot be used withtruncate
orexisting
. -
existing
-
If
true
, the file must already exist. If the file does not exist, an error is thrown. Cannot be used withcreate
. -
append
Requires Gecko 27 -
If
true
, the file will be opened for appending, meaning the equivalent of.setPosition(0, POS_END)
is executed before each write. The default istrue
, i.e. opening a file for appending. Specifyappend: false
to open the file in regular mode.
-
-
options
Optional -
Platform-specific options for opening the file. For advanced users only. Most users will never have need for these options. To specify options, pass an object that may contain some of the following flags:
-
unixFlags
-
(ignored under non-Unix platforms) If specified, file opening flags, as per libc function
open
. If unspecified, build these flags from the contents ofmode
. You can build these flags from values OS.Constants.libc.O_*. -
unixMode
-
(ignored under non-Unix platforms) If specified, file creation mode, as per libc function
open
. If unspecified, files are created with a default mode of 0600 (file is private to the user, the user can read and write). You can build this mode from valuesOS.Constants.libc.S_I*
. -
winShare
-
(ignored under non-Windows platforms) If specified, a sharing policy (how access to file is shared among different processes), as per Windows function
CreateFile
. If unspecified, files are opened with a default sharing policy (file is not protected against being read/written/removed by another process or another use in the same process). You can build this policy from constants OS.Constants.Win.FILE_SHARE_*. -
winSecurity
-
(ignored under non-Windows platforms) If specified, a security policy, as per Windows function
CreateFile
. If unspecified, no security attributes. -
winAccess
-
(ignored under non-Windows platforms) If specified, access mode (read, write, both or neither), as per Windows function
CreateFile
. This also requires optionwinDisposition
and this replaces argumentmode
. If unspecified, value is built frommode
. -
winDisposition
-
(ignored under non-Windows platforms) If specified, disposition mode, as per Windows function
CreateFile
. This also requires optionwinAccess
and this replaces argumentmode
. If unspecified, value is built frommode
.
-
Returns
An instance of OS.File
representing the expected file.
close
that file once you have finished it, to ensure that you are not blocking the rest of the process.The runtime will also do its best to eventually close files that are not used, but you should not rely upon this, as it can depend on many factors that you cannot control.
When opening files for writing, they will be opened for appending unless you specify append: false
in Gecko 27 and later. In Gecko 26 and ealier, on platforms other than Windows, the files will be opened for appending unless you specify explicit unixFlags
or open the file with either create
or truncate
flags. In Gecko 26 and ealier on Windows, files will never be opened for appending.
To open an existing file for writing without appending in a compatible way on all platforms in both, Gecko 27 and later and Gecko 26 and earlier, you should specify both, the append
flag and unixFlags
.
// Open a file for writing without appending to it. // Under Unix, you'll have to specify your own unixFlags for Gecko < 27 to avoid append mode. var options = {}; if (OS.Constants.libc) { // Own flags omitting O_APPEND, e.g. options.unixFlags = OS.Constants.libc.O_CREAT | OS.Constants.libc.O_WRONLY; } // For Gecko >= 27, it is enough, but crucial, to set the correct append flag. var outfile = OS.File.open("file.tmp", {write: true, append: false}, options); try { // ... do something with that file } finally { outfile.close(); }
Examples
Open a file for reading
var file = OS.File.open("/etc/password"); // Open a file for reading try { // ... do something with that file } finally { file.close(); }
Open a file with Unix-specific options
// Prepare opening options: under Unix, the user can only read and modify the file. var options = { unixMode: OS.Constants.S_IRUSR | OS.Constants.S_IWUSR }; var outfile = OS.File.open("file.tmp", {create: true}, options); // Open a file for writing. If the file already exists, fail. try { // ... do something with that file } finally { outfile.close(); }
OS.File.openUnique()
Requires Gecko 27.0
Creates and opens a file with a unique name. By default, generate a random HEX number and use it to create a unique new file name.
object openUnique( in string path, [optional] in object options ) throws OS.File.Error
Arguments
-
path
- The full native name of the file to open.
-
options
Optional -
Additional options for file opening. This implementation interprets the following fields:
-
humanReadable
-
If
true
, create a new filename appending a decimal number. ie: filename-1.ext, filename-2.ext. Iffalse
use HEX numbers ie: filename-A65BC0.ext -
maxAttempts
- Used to limit the amount of tries after a failed file creation. Default is 99.
-
Returns
An object contains A file object{file} and the path{path}.
Throws
-
OS.File.Error
- If the file could not be opened.
OS.File.copy()
Copy a file.
void copy( in string sourcePath, in string destPath [optional] in object options) throws OS.File.Error
Arguments
-
sourcePath
- The full path of the file to copy. At the time of this writing, this function does not copy directories.
-
destPath
- The full path of the destination. Note that this is not a directory but a file.
-
options
Optional - An optional object used to control the behavior of this function. You may pass an object with a subset of the following fields:
-
noOverwrite
-
If
destPath
already exists, do not overwrite it, but rather throw an exception.
Throws
-
OS.File.Error
- In case of any error, in particular if the file does not exist.
- To avoid erasing the destination file, it is much faster to use option
noOverwrite
than to check manually whether the file exists. - This operation is OS-optimized under MacOS X (native operation
copyfile
), Linux/Android (native operationsplice
) and Windows (native operationCopyFile
).
OS.File.exists()
Determine whether a file exists.
bool exists( in string path )
Arguments
-
path
- The name of the file.
Returns
true
if the file exists, false otherwise.
OS.File.getCurrentDirectory()
Return the current directory.
string getCurrentDirectory()
Returns
The path to the current directory.
OS.File.makeDir()
Create a new directory
void makeDir( in string path, [optional] in object options ) throws OS.File.Error
Arguments
-
path
- The full name of the directory to create.
-
options
Optional - Platform-specific options for creating the directory. For advanced users only. Most users will never have need for these options. To specify options, pass an object that may contain some of the following flags:
-
unixMode
-
(ignored under non-Unix platforms) If specified, file creation mode, as per libc function mkdir. If unspecified, directories are created with a default mode of 0600 (file is private to the user, the user can read and write). You can build this mode from values
OS.Constants.libc.S_I*
. -
winSecurity
-
(ignored under non-Windows platforms) If specified, a security policy, as per Windows function
CreateDirectory
. If unspecified, no security attributes.
OS.File.move()
Move a file.
move( in string sourcePath, in string destPath [optional] in object options ) throws OS.File.Error
Arguments
-
sourcePath
-
The full path of the file to move. At the time of this writing, the behavior of this function is unspecified if
sourcePath
is a directory. -
destPath
-
The full path of the destination. At the time of this writing, the behavior of this function is unspecified if
destPath
is a directory. -
options
Optional -
An optional object used to control the behavior of this function. You may pass an object with a subset of the following fields:
-
noOverwrite
-
If
destPath
already exists, do not overwrite it, but rather throw an exception.
-
Throws
-
OS.File.Error
- In case of any error, in particular if the file does not exist.
OS.File.read()
Read the contents of a file
Uint8Array read( in string path, [optional] in number bytes ) throws OS.File.Error
Arguments
-
path
- The full path to the file to read.
-
bytes
Optional - The number of bytes to read. If unspecified, read the file to the end.
Returns
An array holding the bytes
bytes (or less if the file did not contain as many bytes).
Throws
-
OS.File.Error
- In case of any error, in particular if the file does not exist or if the process does not have the authorization to read it.
OS.File.remove()
Remove an existing file.
void remove( in string path [optional] in object options ) throws OS.File.Error
Arguments
-
path
- The full name of the file to remove. At the time of this writing, this function does not remove directories.
-
options
- Ignored for the moment.
Throws
-
OS.File.Error
- In case of any error, in particular if the file does not exist.
OS.File.removeEmptyDir()
Remove an empty directory.
void removeEmptyDir( in string path ) throws OS.File.Error
Arguments
-
path
- The full path to the empty directory.
Throws
-
OS.File.Error
- In case of any error, in particular if the directory does not exist.
OS.File.removeDir()
Requires Gecko 27
Remove an existing directory and its contents.
void removeDir( in string path [optional] in object options ) throws OS.File.Error
Arguments
-
path
- A string representing the name of the file to remove. At the time of this writing, this function does not remove directories.
-
options
- An object that may contain the following fields
-
ignoreAbsent
- If false, this function will throw an error if the directory doesn't exist.
-
ignorePermissions
- If true, this function will remove the directory even when lacking write permissions.
Throws
-
OS.File.Error
- In case of any error, in particular if path isn't a directory.
OS.File.setCurrentDirectory()
Change the current directory of the process.
void setCurrentDirectory( in string path ) throws OS.File.Error
Arguments
-
path
- The full path to use as current directory.
Throws
-
OS.File.Error
- In case of any error, in particular if the path to the directory does not exist.
OS.File.setDates()
Set the last access and modification date of the file.
The time stamp resolution is 1 second at best, but might be worse depending on the platform, file system, etc.
void setDates( in string path, in Date|number accessDate, in Date|number modificationDate )
Arguments
- path
- The complete path to the file.
- accessDate
- The last access date. If numeric, milliseconds since epoch. If omitted or null, the current date will be used.
- modificationDate
- The last modification date. If numeric, milliseconds since epoch. If omitted or null, the current date will be used.
Throws
-
OS.File.Error
- In case of any error, in particular if the path does not represent an existing file.
OS.File.stat()
Obtain information about a file, such as size, creation date, etc.
File.Info stat( in string path ) throws OS.File.Error
Arguments
-
path
- The full path to the file.
Returns
An instance of File.Info holding information about a file.
Throws
-
OS.File.Error
- In case of any error, in particular if the path to the file does not exist.
stat()
is much faster than calling function OS.File.stat().
OS.File.writeAtomic()
Write data to a file. Data is first written to a temporary file, then flushed, then the temporary file is used to overwrite the destination file. This makes it extremely unlikely that the destination file can be corrupted during the call to this function by battery failure, the process being stopped or any other such incident. Note that it is generally not possible to provide a 100% guarantee of such properties.
void writeAtomic( in string path, in ArrayBufferView data, in object options ) throws OS.File.Error
Arguments
-
path
- The full path to the destination file.
-
data
-
An
ArrayBufferView
holding the data to write. -
options
- An object that may contain the following fields:
-
tmpPath
-
The full path to a file that may be used as a temporary buffer. This file must be on the same device as path. In case of doubt,
path + ".tmp"
is generally a good value fortmpPath
. -
noOverwrite
-
If specified and true, and if
path
already exists, this function will throw an error without overwritingpath
.
Throws
- OS.File.Error
-
In case of any error, in particular if the destination file cannot be overwritten, or if
tmpPath
is not on the same device aspath
.
Instances of OS.File
To obtain an instance of OS.File, use function OS.File.open
.
Methods overview
void close() |
void flush() |
number getPosition() |
number read([optional] in number bytes) |
number readTo(out ArrayBufferView dest, [optional] in object options) |
void setDates(in Date|number accessDate, in Date|number modificationDate); |
void setPosition(in number bytes) |
File.Info stat() |
number write(in ArrayBufferView source, [optional] in object options) |
Attributes
fd |
(platform-specific) | (read-only) For advanced users only. A low-level opaque data structure holding the system handle for the file. Under Windows, this is a file HANDLE and under Unix, this is a file descriptor. Use this with the Platform-Specific Low-Level API. |
Methods
close()
Close a file and release any associated resource.
Once the file is closed, any attempt to call methods of the file object will raise an error.
close
that file once you have finished it to make sure that you are not blocking the rest of the process.void close() throws OS.File.Error
flush()
Flushes the file's internal buffers, ensuring that all data still in these buffers is now written to disk.
Disk flushes are very expensive and therefore should be used carefully, sparingly and only in scenarios where it is vital that data survives system crashes. Even though the function will be executed off the main-thread, it might still affect the overall performance of any running application.
void flush() throws OS.File.Error
getPosition()
Return the current position in the file.
number getPosition() throws OS.File.Error
Returns
The current position in the file, as a number of bytes from the start.
Throws
-
OS.File.Error
- If the file is closed.
read()
Read bytes from this file to a new buffer. Bytes are read from the current position in the file and the position is advanced accordingly.
UInt8Array read( [optional] in number bytes ) throws OS.File.Error
Arguments
-
bytes
Optional -
If specified, read
bytes
bytes, or less if the file does not contain that many bytes. If unspecified, read all the remaining bytes from this file.
Returns
An array containing the bytes read.
Throws
-
OS.File.Error
- In case of I/O error.
readTo()
Read bytes from the file to an existing array. Bytes are read from the current position in the file and the position is advanced accordingly.
number readTo( out ArrayBufferView dest, [optional] in object options ) throws OS.File.Error
Arguments
-
dest
- The buffer in which to store the bytes.
-
options
Optional - An object that may contain some of the following fields:
-
bytes
-
An upper bound to the number of bytes to read from the file. If unspecified, read up to
dest.byteLength
bytes. If specified, this must be less thandest.byteLength
.
Returns
The number of bytes effectively read from the file.
Throws
-
OS.File.Error
- In case of any I/O error.
-
TypeError
-
If
options.bytes
is specified and is larger thandest.byteLength
.
setDates()
Set the last access and modification date of the file.
The time stamp resolution is 1 second at best, but might be worse depending on the platform, file system, etc.
void setDates( in Date|number accessDate, in Date|number modificationDate )
Arguments
- accessDate
- The last access date. If numeric, milliseconds since epoch. If omitted or null, the current date will be used.
- modificationDate
- The last modification date. If numeric, milliseconds since epoch. If omitted or null, the current date will be used.
Throws
-
OS.File.Error
- In case of any error, in particular if the path does not represent an existing file.
setPosition()
Change the current position in the file.
void setPosition( in number offset, in object origin ) throws OS.File.Error
Arguments
-
offset
- The new position, as a number of bytes from the origin.
-
origin
-
One of the following:
OS.File.POS_START
(bytes are counted from the start of the file);OS.File.POS_CUR
(bytes are counted from the current position in the file);OS.File.POS_END
(bytes are counted from the end of the file).
Throws
-
OS.File.Error
- In case of any error, in particular if the new position is before the start of the file, or if the file is closed.
stat()
Obtain information about the file, such as size, creation date, etc.
File.Info stat() throws OS.File.Error
Returns
An instance of File.Info holding information about the file.
Throws
-
OS.File.Error
- In case of any error, in particular if the file is closed.
write()
Write bytes from a buffer to this file.
Note that, by default, this function may perform several I/O operations to ensure that the buffer is fully written.
number write( in ArrayBufferView source [optional] in object options ) throws OS.File.Error
Arguments
-
source
- The array in which the the bytes are stored.
-
options Optional
- An object that may contain some of the following fields:
-
bytes
-
An upper bound to the number of bytes to write to the file. If unspecified, write up to
source.byteLength
bytes. If specified, this must be less thansource.byteLength
.
Returns
The number of bytes effectively written to the file.
Throws
- OS.File.Error
- In case of any I/O error.
- TypeError
-
If
options.bytes
is specified and is larger thansource.byteLength
.