Cette traduction est incomplète. Aidez à traduire cet article depuis l'anglais.
Cette page explique comment utiliser File I/O depuis le thread principal. Pour d'autres utilisations de OS.File, voir OS.File.
Utilisation d'OS.File depuis le thread principal
Pour importer OS.File dans votre code chrome, ajoutez les ligne suivante au début de votre script:
Components.utils.import("resource://gre/modules/osfile.jsm");
Pour importer OS.File dans votre code main.js, ajoutez les lignes suivantes au début de votre script:
const {Cu} = require("chrome");
// To read content from file
const {TextDecoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {});
// To read & write content to file
const {TextDecoder,
TextEncoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {});
Promises
Avant d'utiliser OS.File depuis le thread principal, vous avez besoin d'une certaine compréhension de la bibliothèque Promise.
Voir la documentation object Promise
pour plus de détails.
OS.File fonctionne très bien avec Task.jsm.
Exemple: Lire le contenu d'un fichier sous forme de texte
L'extrait suivant ouvre un fichier "file.txt" et lit son contenu sous forme de chaîne, en utilisant l'encodage par défaut (utf-8).
Le contenu est lu de manière asynchrone. Le résultat est une Promise.
let decoder = new TextDecoder(); // This decoder can be reused for several reads let promise = OS.File.read("file.txt"); // Read the complete file as an array promise = promise.then( function onSuccess(array) { return decoder.decode(array); // Convert this array to a text } );
Exemple: Ecrire une chaîne dans un fichier
L'extrait suivant écrit le texte "Ceci est un texte" sous forme de chaîne dans "file.txt", en utilisant l'encodage par défaut (utf-8). Il utilise une écriture atomique pour veiller à ce que le fichier ne soit pas modifiée si, pour une raison quelconque, l'écriture ne peut pas se réaliser complètement (généralement parce que l'ordinateur est éteint, la batterie est épuisée, ou l'application est arrêtée.)
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 let promise = OS.File.writeAtomic("file.txt", array, // Write the array atomically to "file.txt", using as temporary {tmpPath: "file.txt.tmp"}); // buffer "file.txt.tmp".
La variante suivante fait la même chose, mais échouera si "file.txt" existe déjà:
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 let promise = OS.File.writeAtomic("file.txt", array, // Write the array atomically to "file.txt", using as temporary {tmpPath: "file.txt.tmp", noOverwrite: true}); // buffer "file.txt.tmp".
Exemple: Renommer un fichier
Vous pouvez utiliser OS.File.move
pour renommer un fichier:
let promise = OS.File.move("oldname.txt", "newname.txt", {noOverwrite:true});
Voici un exemple qui a rebaptise test.txt
en testRenamed.txt
si le fichier se trouve dans le répertoire C:\Jean\
var promise = OS.File.move(OS.Path.join('C:', 'Jean', 'test.txt'), OS.Path.join('C:', 'Jean', 'testRenamed.txt')); promise.then( function() { console.log('rename successful') }, function(aRejectReason) { console.log('rename failed, aRejectReason = ', aRejectReason) } )
noOverwrite: true
est important, (par défaut false
) si un fichier avec le même nom existe déjà dans le répertoire, il ne sera plus là après cette opération "renommer", qui est un "mouvement".
Exemple: Copier un fichier
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.
let promise = OS.File.copy("oldname.txt", "newname.txt");
Exemple: Manipulation de chemin
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, this is generally "%APPDATA%\Local\temp\%PROFILENAME%"\sessionstore.js // etc.
Exemple: Déterminer si un fichier est un répertoire
The following snippet determines if some path represents a file or a directory:
let promise = OS.File.stat(somePath); promise = promise.then( function onSuccess(stat) { if (stat.isDir) { // The path represents a directory } else { // The path represents a file, not a directory } }, function onFailure(reason) { if (reason instanceof OS.File.Error && reason.becauseNoSuchFile) { // The file does not exist } else { // Some other error throw reason; } } );
Exemple: copier un fichier par morceaux
The following snippet writes a (presumably large) buffer by chunks. Note that this snippet is useful as a demonstration of complex asynchronous programming with OS.File – in most cases, function OS.File.writeAtomic
is a better choice.
let writeStream = function writeStream(data, outFile, chunkSize) { let view = new Uint8Array(data); let loop = function loop(pos) { // Define a recursive asynchronous loop. if (pos <= view.byteLength) { // Note: Should this be pos >= view.byteLength ? return Promise.resolve(true); // Loop end. } let promise = file.write(view.subarray(pos, chunkSize)); // Write a subset of |data| return promise.then(function onSuccess(bytes) { return loop(pos + bytes); // ... and loop. }); }; let promise = loop(0); // Enter the loop. promise = promise.then(function onSuccess() { // Once loop is complete, finalize. file.close(); }, function onError(reason) { file.close(); throw reason; }); return promise; }
Or a variant using Task.js (or at least the subset already present on mozilla-central):
let writeStream = function writeStream(data, outFile, chunkSize) { return Task.spawn(function() { let view = new Uint8Array(data); let pos = 0; while (pos < view.byteLength) { pos += yield outFile.write(view.subarray(pos, chunkSize)); } outFile.close(); }).then( null, function onFailure(reason) { outFile.close(); throw reason; } ); }
Exemple: Enregistrer un canvas sur le disque
This exmaple uses Image
to load an image from a path (note: if your path is a file on disk you must use local file; this is accomplished with OS.Path.toFileURI
, which accepts a string). After image loads it then draws it to canvas
, makes it a blob
, and uses FileReader
to turn it into ArrayBuffer(View)
, then uses OS.File.writeAtomic to save to disk.
var img = new Image();
img.onload = function() {
var canvas = document.createElementNS('https://www.w3.org/1999/xhtml', 'canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
(canvas.toBlobHD || canvas.toBlob).call(canvas, function(b) {
var r = Cc['@mozilla.org/files/filereader;1'].createInstance(Ci.nsIDOMFileReader);
//new FileReader();
r.onloadend = function() {
// r.result contains the ArrayBuffer.
var writePath = OS.Path.join(OS.Constants.Path.desktopDir, 'savedImage.png');
var promise = OS.File.writeAtomic(writePath, new Uint8Array(r.result), { tmpPath: writePath + '.tmp' });
promise.then(
function(aVal) {
console.log('successfully saved image to disk');
},
function(aReason) {
console.log('writeAtomic failed for reason:', aReason);
}
);
};
r.readAsArrayBuffer(b);
}, 'image/png');
};
//var path = OS.Path.toFileURI(OS.Path.join(OS.Contants.Path.desktopDir, 'my.png')); //do it like this for images on disk
var path = 'https://mozorg.cdn.mozilla.net/media/img/firefox/channel/toggler-beta.png?2013-06'; //do like this for images online
img.src = path;
Exemple: Ajouter au fichier
This example shows how to use open
, write
, and close
to append to a file. If the file does not exist, it is created. At the time of this writing, write
does not support encoding
option so the text to be written has to be encoded with TextEncoder
. This example also shows the resolve value of open (an instance of OS.File, this is a file, so you can do any of the methods on it found here), write
(a number indicating bytes written), and close
(undefined
, meaning there is no resolve value).
var pth = OS.Path.join(OS.Constants.Path.desktopDir, 'app.txt'); OS.File.open(pth, {write: true, append: true}).then(valOpen => { console.log('valOpen:', valOpen); var txtToAppend = '
append some text\n'; var txtEncoded = TextEncoder().encode(txtToAppend); valOpen.write(txtEncoded).then(valWrite => { console.log('valWrite:', valWrite); valOpen.close().then(valClose => { console.log('valClose:', valClose); console.log('successfully appended'); }); }); });
Objet Global OS.File
Aperçu des Méthodes
Promise<File> open(in string path, [optional] in object mode, [optional] in object options); |
Promise<object> openUnique(in string path, [optional] in object options); |
Promise<void> copy(in string sourcePath, in string destPath, [optional] in object options); |
Promise<bool> exists(in string path); |
Promise<string> getCurrentDirectory(); |
Promise<void> makeDir(in string path, [optional] in object options); |
Promise<void> move(in string sourcePath, in string destPath); |
Promise<Uint8Array> read(in string path, [optional] in object options); |
Promise<void> remove(in string path, [optional] in object options); |
Promise<void> removeEmptyDir(in string path, [optional] in object options); |
Promise<void> removeDir(in string path, [optional] in object options); |
Promise<void> setCurrentDirectory(in string path); |
Promise<void> setDates(in string path, in Date|number accessDate, in Date|number modificationDate); |
Promise<void> setPermissions(in string path, in object options ); |
Promise<File.Info> stat(in string path, [optional] in object options); |
Promise<void> unixSymLink(in string targetPath, in string createPath); |
Promise<void> writeAtomic(in string path, in ArrayView data, in object options); |
Methods
OS.File.open()
Use method OS.File.open()
to open a file.
Promise<File> open( in string path, [optional] in object mode, [optional] in object options )
Arguments
path
- The full native name of the file to open.
mode
Facultatif- 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, unless
create
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. See bug 924858. Starting with Gecko 27, you may use theappend
flag instead. For an example using append see here. truncate
|trunc
- 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, throw an error. Cannot be used withtruncate
orexisting
. existing
- If
true
, the file must already exist. If the file does not exist, throw an error. Cannot be used withcreate
. append
- 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
Facultatif- Platform-specific options for opening the file. For advanced users only. Most users will never have need of 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, 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, 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
.
Promise resolves to
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.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 earlier, 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 earlier 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. Task.spawn(function() { // 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 = yield OS.File.open("file.tmp", {write: true, append: false}, options); try { // ... do something with that file } finally { yield outfile.close(); } });
Example of opening file and keeping it locked
This uses Tasks.jsm to open a file and keep it open. When you are done with it, like in shutdown of restartless add-on, you should close the file so it becomes editable again.
let options = { winShare: 0 // Exclusive lock on Windows }; if (OS.Constants.libc.O_EXLOCK) { // Exclusive lock on *nix options.unixFlags = OS.Constants.libc.O_EXLOCK; } let file = yield OS.File.open(..., options);
Then when you want to unlock the file so it can be edited from other places, close the file.
file.close();
This example is from Stackoverflow: OS.File check last modified date before OS.read
OS.File.openUnique()
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.
Promise<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
Facultatif- Additional options for file opening. This implementation interprets the following fields:
humanReadable
- If
true
, create a new filename appending a decimal number, e.g., filename-1.ext, filename-2.ext. Iffalse
use hex numbers, e.g., filename-A65BC0.ext. maxAttempts
- Used to limit the amount of tries after a failed file creation. Default is 99.
Promise resolves to
An object contains a file object{file} and the path{path}.
Promise can be rejected with
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
Facultatif- 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 launch an exception.
Promise can be rejected with
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 OS X (native operation
copyfile
), Linux/Android (native operationsplice
), and Windows (native operationCopyFile
).
OS.File.exists()
Determine whether a file exists
Promise<bool> exists( in string path )
Arguments
path
- The name of the file
Promise resolves to
true if the file exists, false otherwise
OS.File.getCurrentDirectory()
Return the current directory
Promise<string> getCurrentDirectory()
Promise resolves to
The path to the current directory.
Safety note: Recall that the current directory can change during the execution of the process. Therefore, the information returned by this function may be false by the time you receive it.
OS.File.makeDir()
Create a new directory
Promise<void> makeDir( in string path, [optional] in object options ) throws OS.File.Error
Arguments
path
- The full name of the directory to create.
options
Facultatif- Options for creating the directory. To specify options, pass an object that may contain some of the following flags:
ignoreExisting
- If
true
, succeed even if the directory already exists (default behavior). Otherwise, fail if the directory already exists. NOTE: Iffrom
is specified then even ifignoreExisting
is specified asfalse
, it will not fail due to pre-existence of directories, because thefrom
option tellsmakeDir
to make the folders if not found. 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. from
- If specified, the call to
makeDir
creates all the ancestors ofpath
that are descendents offrom
. Note thatfrom
and its existing descendents must be user-writeable and thatpath
must be a descendent offrom
.
OS.File.move()
Move a file.
Promise<void> move( in string sourcePath, in string destPath [optional] in object options )
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
Facultatif- 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 launch an exception. noCopy
- If moving the file would require a copy (i.e. if the destination path resides on another drive/device/file system as the source path), fail.
Promise can be rejected with
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
Promise<Uint8Array> read( in string path, [optional] in number bytes )
Arguments
path
- The full path to the file to read.
bytes
Facultatif- The number of bytes to read. If unspecified, read the complete file.
Promise resolves to
An array holding bytes bytes (or less if the file did not contain as many bytes).
Promise can be rejected with
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.
- As of Firefox 30, OS.File.read() takes an options object as second argument.
Promise<Uint8Array> read( in string path, [optional] in object options )
Arguments
path
- The full path to the file to read.
options
Facultatif- An optional object used to control the behavior of this function. You may pass an object with a subset of the following fields:
bytes
- The number of bytes to read. If unspecified, read the complete file.
encoding
- Instead of using
TextDecoder
, you can supply a string to this option. For example, instead of:let decoder = new TextDecoder(); let promise = OS.File.read("file.txt"); promise = promise.then( function onSuccess(array) { return decoder.decode(array); // Convert this array to a text } );
You can simply do:let promise = OS.File.read("file.txt", { encoding: "utf-8" }); promise = promise.then( function onSuccess(text) { return text; // text is a string } );
OS.File.remove()
Remove an existing file.
Promise<void> remove( in string path, [optional] in object options )
Arguments
path
- A string representing the path of the file to remove. At the time of this writing, this function does not remove directories.
- options Facultatif
- An optional object used to control the behavior of this function. You may pass an object with a subset of the following fields:
ignoreAbsent
- Succeed if the file doesn't exist.
Promise can be rejected with
OS.File.Error
- In case of any error, in particular if the file does not exist.
OS.File.removeEmptyDir()
Remove an empty directory
Promise<void> removeEmptyDir( in string path, [optional] in object options )
Arguments
path
- The complete path to the directory.
- options Facultatif
- An optional object used to control the behavior of this function. You may pass an object with a subset of the following fields:
ignoreAbsent
- Succeed if the directory doesn't exist.
Promise can be rejected with
OS.File.Error
- In case of any error, in particular if the file does not exist.
OS.File.removeDir()
Remove an existing directory and its contents.
Promise<void> removeDir( in string path, [optional] in object options )
Arguments
path
- A string representing the name of the file to remove.
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.
Promise can be rejected with
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.
Promise<void> setCurrentDirectory( in string path )
Arguments
path
- The complete path to use as current directory.
Promise can be rejected with
OS.File.Error
- In case of any error, in particular if the path does not represent an existing directory.
OS.File.setDates()
Set the last access and modification date of the file.
The time stamp resolution is one second at best, but might be worse depending on the platform, file system, etc.
Promise<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.
Promise can be rejected with
OS.File.Error
- In case of any error, in particular if the path does not represent an existing file.
-
OS.File.setPermissions()
Sets the file's access permission bits.
Promise<void> setPermissions( in string path, in object options )
Arguments
- path
- The complete path to the file.
- options
- The new attributes to set
winAttributes
- This is an object with following optional keys. Ignored under non-Windows platforms.
hidden
- Boolean. Set to true to make the target hidden, or false to make it visible.
readOnly
- Boolean. Set to true to make the target "read only".
system
- Boolean. Toggles the "system" attribute, this is equivalent .
unixMode
- Number. This is an number can be created with the constants available in
OS.Constants.libc.S_I*
orOS.Constants.libc.S_O*
. Ignored under non-Unix platforms. To make a file hidden on Unix based platforms, including Mac, simply rename the file withOS.File.move
to have "." at the start of the file name. unixHonorUmask
- Toggles the
OS.Constants.Sys.umask
flag. Ignored under non-Unix platforms.. -
Promise can be rejected with
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.
Promise<File.Info> stat( in string path )
Arguments
path
- The complete path to the file.
Promise resolves to
An instance of File.Info holding information about a file.
Promise can be rejected with
OS.File.Error
- In case of any error, in particular if the path does not represent an existing file.
stat()
is much faster than calling function OS.File.stat().OS.File.unixSymLink()
Create a symoblic link file, also known as "Alias" files on Mac OS. This is similar to "Shortcut" files on Windows systems. This function is specific to UNIX baed systems such as Linux and Mac OS X.
Promise<undefined> unixSymLink( in string pathTarget, in string pathCreate )
Arguments
pathTarget
- The complete path to the file that should be launced by the symbolic link.
pathCreate
- The complete path to the file that should launch target. The file extension should be
.link.
Promise resolves to
undefined
Promise can be rejected with
OS.File.Error
- In case of any error. If the file exists already, unixErrorco of 17 will be returned.
OS.File.writeAtomic()
Write data to a file, atomically.
Unlike a regular write
, this operation ensures that, until the contents are fully written, the destination file is not modified.
Promise<void> writeAtomic( in string path, in ArrayBufferView data, in object options )
Arguments
path
- The full path to the destination file.
data
- An ArrayBufferView holding the data to write.
As of Firefox 37, this method will neuter the array buffer.
options
- An object that may contain the following fields
tmpPath
- If
null
or unspecified, write the data directly topath
. If specified, write the data to a temporary file calledtmpPath
and, once the write is complete, rename the file to replacepath
. Performing this operation is a little slower but also a little safer.tmpPath is required in Firefox 24 or lower version, but optional in Firefox 25 or higher version
noOverwrite
- If specified and true, and if
path
already exists, this function will throw an error without overwritingpath
. flush
- If
false
or unspecified, return immediately once the write is complete. Iftrue
, before writing, force the operating system to write its internal disk buffers to the disk. This is considerably slower (not just for the application but for the whole system) and more battery expensive but also safer: if the system shuts down improperly (typically due to a kernel freeze or a power failure) or if the device is disconnected before the buffer is flushed, the file has more chances of not being corrupted. backupTo
- Available since Firefox 30. If specified, backup the destination file as
backupTo
. Note that this function renames the destination file before overwriting it. If the process or the operating system freezes or crashes during the short window between these operations, the destination file will have been moved to its backup. encoding
- Available since Firefox 22. Instead of using
TextEncoder
, you can supply a string to this option. For example, instead of:let encoder = new TextEncoder(); let array = encoder.encode("This is some text"); let promise = OS.File.writeAtomic("file.txt", array, {tmpPath: "file.txt.tmp"});
You can simply do:let promise = OS.File.writeAtomic("file.txt", "This is some text", { encoding: "utf-8", tmpPath: "file.txt.tmp" })
In a few extreme cases (hardware failure during the write, user unplugging disk during the write, etc.), data may be corrupted. If your data is user-critical (e.g., preferences, application data), you may wish to consider adding options
tmpPath
and/or flush
to reduce the likelihood of corruption, as detailed above. Note that no combination of options can be guaranteed to totally eliminate the risk of corruption.data
before the operation is complete is a very bad idea.Promise can be rejected with
- 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
Promise<void> close() |
Promise<void> flush() |
Promise<number> getPosition() |
Promise<number> read([optional] in number bytes) |
Promise<void> setDates(in Date|number accessDate, in Date|number modificationDate); |
Promise<void> setPosition(in number bytes) |
Promise<File.Info> stat() |
Promise<number> write(in ArrayBufferView source, [optional] in object options) |
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.
An example is seen here. In this example the contents is not written to file until .close is called.
close
that file once you have finished it to make sure that you are not blocking the rest of the process.Promise<void> close()
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.
Promise<void> flush()
getPosition()
Return the current position in the file.
Promise<number> getPosition()
Promise resolves to
The current position in the file, as a number of bytes from the start.
Promise can be rejected with
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.
Promise<Uint8Array> read( [optional] in number bytes )
Arguments
bytes
- 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.
Promise resolves to
An array containing the bytes read.
Promise can be rejected with
OS.File.Error
- In case of I/O error.
setDates()
Set the last access and modification date of the file.
The time stamp resolution is one second at best, but might be worse depending on the platform, file system, etc.
Promise<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.
Promise can be rejected with
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.
Promise<void> setPosition( in number offset, in object origin )
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)
Promise can be rejected with
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.
Promise<File.Info> stat()
Promise resolves to
An instance of File.Info holding information about the file.
Promise can be rejected with
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.
An example is seen here.
Promise<number> write( in ArrayBufferView source [optional] in object options )
Arguments
source
- The array in which the the bytes are stored.
As of Firefox 37, this method will neuter the array buffer.
options
Facultatif- 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
.
Promise resolves to
The number of bytes effectively written to the file.
Promise can be rejected with
OS.File.Error
- In case of any I/O error.
TypeError
- If
options.bytes
is specified and is larger thansource.byteLength
.