Search completed in 1.27 seconds.
FileSystemDirectoryEntry.getFile() - Web APIs
options Optional An object based on the FileSystemFlags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists. These options are currently not useful in Web contexts. ...
...nied for security reasons. FileError.TYPE_MISMATCH_ERR The path specified is not a file; it's probably a directory, but might be an unsupported file descriptor such as a pipe; this depends on the user agent to some extent. FileSystemFlags The options parameter is an object which is based on the FileSystemFlags dictionary; it provides flags which make it possible to adjust the behavior of the
getFile() method. create Optional If this property is true, and the requested file or directory doesn't exist, the user agent should create it. The default is false. The parent directory must already exist. exclusive Optional If true, and the create option is also true, the file must not exist prior to issuing the call. Instead, it must be possible for it to be created newly at call time. The defau...
...is false. Values and results The table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. Option values File/directory condition Result create exclusive false n/a[1] Path exists and matches the desired type (depending on whether the function called is
getFile() or getDirectory() The successCallback is called with a FileSystemFileEntry if
getFile() was called or a FileSystemDirectoryEntry if getDirectory() was called. false n/a[1] Path exists but doesn't match the desired type The errorCallback is called with an appropriate error code (if the callback was provided). true false Path exists The existing file or dire...
...And 4 more matches
PR_GetFileInfo
Gets information about a file with a specified pathname. File size is expressed as a 32-bit integer. Syntax #include <prio.h> PRStatus PR_
GetFileInfo( const char *fn, PRFileInfo *info); Parameters The function has the following parameters: fn The pathname of the file to get information about. info A pointer to a file information object (see PRFileInfo). On output, PR_
GetFileInfo writes information about the given file to the file information object. Returns One of the following values: If the file information is successfully obtained, PR_SUCCESS. If the file information is not successfully obtained, PR_FAILURE. Description PR_
GetFileInfo stores information about the file with the specified pathname in the PRFileInfo structure pointed to by info. The file size is returne...
...ing values: If the file information is successfully obtained, PR_SUCCESS. If the file information is not successfully obtained, PR_FAILURE. Description PR_
GetFileInfo stores information about the file with the specified pathname in the PRFileInfo structure pointed to by info. The file size is returned as an unsigned 32-bit integer. See Also For the 64-bit version of this function, see PR_
GetFileInfo64. To get equivalent information on a file that's already open, use PR_GetOpenFileInfo. ...
PR_GetFileInfo64
Gets information about a file with a specified pathname. File size is expressed as a 64-bit integer. Syntax #include <prio.h> PRStatus PR_
GetFileInfo64( const char *fn, PRFileInfo64 *info); Parameters The function has the following parameters: fn The pathname of the file to get information about. info A pointer to a 64-bit file information object (see PRFileInfo64). On output, PR_
GetFileInfo64 writes information about the given file to the file information object. Returns One of the following values: If the file information is successfully obtained, PR_SUCCESS. If the file information is not successfully obtained, PR_FAILURE. Description PR_
GetFileInfo64 stores information about the file with the specified pathname in the PRFileInfo64 structure pointed to by info. The f...
...values: If the file information is successfully obtained, PR_SUCCESS. If the file information is not successfully obtained, PR_FAILURE. Description PR_
GetFileInfo64 stores information about the file with the specified pathname in the PRFileInfo64 structure pointed to by info. The file size is returned as an unsigned 64-bit integer. See Also For the 32-bit version of this function, see PR_
GetFileInfo. To get equivalent information on a file that's already open, use PR_GetOpenFileInfo64. ...
HTMLInputElement.mozGetFileNameArray() - Web APIs
The HTMLInputElement.moz
GetFileNameArray() method returns an array of the names of the files that were selected by the user on an HTML input element. Note: This method is Gecko-specific and is not available in other browsers. Also, it throws an error if used in Web pages. Syntax inputElement.moz
GetFileNameArray(aLength, aFileNames); Parameters aLength If specified, will receive the number of file names in the returned array. aFileNames Is an array into which the file names are placed. ...
...s Gecko-specific and is not available in other browsers. Also, it throws an error if used in Web pages. Syntax inputElement.moz
GetFileNameArray(aLength, aFileNames); Parameters aLength If specified, will receive the number of file names in the returned array. ...
getFile
<< XPCOM API Reference Called by the Directory Service to obtain an nsIFile object corresponding for a given standard path location. The individual platform implementation of nsIDirectoryServiceProvider maps the symbolic path location passed to this function and returns the appropriate nsIFile. nsIFile
getFile( in string aName, out boolean aPersistent ); Parameters aName [in] The symbolic name for a file or directory location. See Symbolic names below for a list of accepted values. XPCOM File System Aliases aPersistent [out] This output parameter indicates to the caller whether or not the returned location is persistent. If true, this lets the Directory Service cache results to improve the performance of directory lookups. If false, then the Directory Service will...
getFiles
<< XPCOM API Reference Summary This method is called by the Directory Service to query an enumeration of file or directory locations. nsISimpleEnumerator
getFiles( in string aName ); Parameters aName [in] The symbolic name for an enumeration of file or directory locations. Return Values The elements of the returned nsISimpleEnumerator instance must support nsIFile and may support nsILocalFile. See Also nsIFile, nsILocalFile, nsISimpleEnumerator ...
FileHandle.getFile() - Web APIs
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. Summary The
getFile method allows to retrieve a read-only snapshot of the handled file in the form of a File object. Syntax var request = instanceOfFileHandle.
getFile(); Return A DOMRequest object. In case of success, the request's result is a File object. Specifications Specification Status Comment FileSystem API Editor's Draft Draft proposal ...
nsIScriptableIO
ublished through a global IO object. For more details about how to use this object, see the File and Stream Guide. network/base/public/nsIScriptableIO.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsISupports A scriptable IO object can be used in an extension or chrome code by referring to the global IO object. ...
...ts from: nsISupports A scriptable IO object can be used in an extension or chrome code by referring to the global IO object. ...
...chrome code by referring to the global IO object. ...
...And 9 more matches
Working With Directories - Archive of obsolete content
u can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. ...
...a file by using nsIScriptableIO.
getFile(). You can access a subdirectory by supplying a directory name as the second argument, or refer to one of the special directories by supplying a null string for the second argument. The first line below with retrieve the directory corresponding to the user's home directory, while the second will retrieve the directory 'myfiles' on the desktop. var dir1 = IO.
getFile("Home", ""); var dir2 = IO.
getFile("Desktop", "myfiles"); To refer to a subdirectory, rather than using a path, use nsIFile.append() to build up a path. For instance: var dir2 = IO.
getFile("Desktop", "myfiles"); dir2.append("pictures"); dir2.append("vacations"); In this example, a subdirectory several levels down is referenced. Each call to nsIFile.append() navigates to a further subdirectory. ...
...about this. Note that nsIFile.append() modifies the file object, rather than returning a new one. Both files and directories are represented using the same kind of object so most of the functions available for nsIFile will work for both. You can check if the object refers to a directory or a file by using nsIFile.isDirectory(). ...
...And 4 more matches
Accessing Files - Archive of obsolete content
forth. Once one of these starting directories is determined, a file reference may be created relative to this. A common case is to write a file in the directory that holds the user's preferences. This is a convenient location where an extension might save a file it needs to use. This directory is referred to as the user's profile directory. ...
...ite a file in the directory that holds the user's preferences. This is a convenient location where an extension might save a file it needs to use. This directory is referred to as the user's profile directory. To get a reference to a File object use nsIScriptableIO.
getFile(). The following example will retrieve a reference to a file named sample.txt located in the profile directory. var file = IO.
getFile("Profile", "sample.txt"); The nsIScriptableIO object is a global object always available within an application or extension which provides a number of useful functions for dealing with files. One such method it provides is nsIScriptableIO.
getFile() which returns a new nsIFile object. The first argument to nsIScriptableIO.
getFile() is the starting directory from which to locate a file. In the exa...
...ate a file. In the example above the word 'Profile' is used, which means start from within the user's profile directory. The actual location of this directory will vary by user and system, so this is a convenient means to refer to a common directory without having to locate it yourself. For a full list of starting directories, see Starting Directories below. The second argument to nsIScriptableIO.
getFile() is the filename to locate, which, here, is 'sample.txt'. The result is that a reference is made to the 'sample.txt' file. It is important to note that this file does not have to exist for a file reference to be valid. That is, nsIScriptableIO.
getFile() will still return a valid file reference even if the file 'sample.txt' does not yet exist. You can check if the file exists by using nsIFile.exi...
...And 3 more matches
Downloading Files - Archive of obsolete content
thod, passing it a URL to download and an nsIFile instance representing the local file name/path. Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm"); const WebBrowserPersist = Components.Constructor("@mozilla.org/embedding/browser/nsWebBrowserPersist;1", "nsIWebBrowserPersist"); var persist = WebBrowserPersist(); var tar
getFile = Services.dirsvc.get("Desk", Ci.nsIFile); tar
getFile.append("file.bin"); // Obtain the privacy context of the browser window that the URL // we are downloading comes from. If, and only if, the URL is not // related to a window, null should be used instead. var privacy = PrivateBrowsingUtils.privacyContextFromWindow(urlSourceWindow); persist.persistFlags = persist.PERSIST_FLAGS_FROM_CACHE ...
...ser window that the URL // we are downloading comes from. If, and only if, the URL is not // related to a window, null should be used instead. var privacy = PrivateBrowsingUtils.privacyContextFromWindow(urlSourceWindow); persist.persistFlags = persist.PERSIST_FLAGS_FROM_CACHE | persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES; persist.saveURI(uriToSave, null, null, null, "", tar
getFile, privacy); If you don't need detailed progress information, you might be happier with nsIDownloader. Downloading Binary Files with a Progress Listener To download a binary file with custom progress listener: Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm"); const WebBrowserPersist = Components.Constructor("@mozilla.org/embedding/browser/nsWebBrowserPersist;1", ...
...If, and only if, the URL is not // related to a window, null should be used instead. var privacy = PrivateBrowsingUtils.privacyContextFromWindow(aURLSourceWindow)...
...And 2 more matches
Index - Web APIs
System API, File and Directory Entries API, FileSystemDirectoryEntry, Files, Method, Non-standard, Reference, getDirectory The FileSystemDirectoryEntry interface's method getDirectory() returns a FileSystemDirectoryEntry object corresponding to a directory contained somewhere within the directory subtree rooted at the directory on which it's called. 1366 FileSystemDirectoryEntry.
getFile() API, File System API, File and Directory Entries API, FileSystemDirectoryEntry, Files, Method, Non-standard, Reference,
getFile The FileSystemDirectoryEntry interface's method
getFile() returns a FileSystemFileEntry object corresponding to a file contained somewhere within the directory subtree rooted at the directory on which it's called. 1367 FileSystemDirectoryEntry.remo...
...is: 1387 FileSystemFlags.create API, Create, File System API, File and Directory Entries API, FileSystemFlags, Files, Flile System API, Non-standard, Offline, Property, Reference The create property on the FileSystemFlags dictionary is used to indicate whether or not the file should be created if it's missing. FileSystemFlags is only used when calling FileSystemDirectoryEntry.
getFile() or FileSystemDirectoryEntry.getDirectory(). 1388 FileSystemFlags.exclusive API, File System API, File and Directory Entries API, FileSystemFlags, Files, Non-standard, Offline, Property, Reference, exclusive The exclusive property on the FileSystemFlags dictionary is used in tandem with the create property to determine whether or not it's acceptable to require that the file ...
... 1389 FileSystemSync API, File API, File System API, Files, Offline, filesystem In the File System API, a FileSystemSync object represents a file system. It has two properties. 1390 FocusEvent API, DOM, DOM Events, Event, Reference The FocusEvent interface represents focus-related events, including focus, blur,...
...And 2 more matches
Starting WebLock
do this, you must get the implementation like we did above. When you have it, QueryInterface for the nsIDirectoryService interface. In this interface, there is a function which allows you to register an nsIDirectoryServiceProvider interface. The interface callback looks like this: [scriptable, uuid(bbf8cab0-d43a-11d3-8cc2-00609792278c)] interface nsIDirectoryServiceProvider: nsISupports { /** *
getFile * * Directory Service calls this when it gets the first request for * a prop or on every request if the prop is not persistent. * * @param prop The symbolic name of the file. * @param persistent TRUE - The returned file will be cached by Directory * Service. Subsequent requests for this prop will * bypass the provider and use the cache. * FALSE - The provider will be asked for this prop * each ti...
... every request if the prop is not persistent. * * @param prop The symbolic name of the file. * @param persistent TRUE - The returned file will be cached by Directory * Service. Subsequent requests for this prop will * bypass the provider and use the cache. * FALSE - The provider will be asked for this prop * each time it is requested. * * @return The file represented by the property. * */ nsIFile
getFile(in string prop, out PRBool persistent); }; Modifying Paths with nsIFile The directory service returns an nsIFile object, but that object points to the application directory and not the file itself. To modify this nsIFile so that it points to the file, you must call the Append method of the nsIFile. Append adds the input string to the path already specified in the nsIFile. On Unix, for example,...
...following code loads the contents of the file referenced by the nsIFile object theFile into the buffer buf: nsCOMPtr<nsILocalFile> localFile = do_QueryInterface(theFile); if (!localFile) return -1; PRBool exists; rv = theFile->Exists(&exists); if (NS_FAILED(rv)) return -1; char *buf = NULL; if (exists) { // determine file size: PRUint32 fs, numread; PRInt64 fileSize; rv = theFile->
GetFileSize(&fileSize); if (NS_FAILED(rv)) return -1; // Converting 64 bit value to unsigned int LL_L2UI(fs, fileSize); FILE* openFile; rv = localFile->OpenANSIFileDesc("rw", &openFile); if (NS_FAILED(rv)) return -1; char *buf = (char *)malloc((fs+1) * sizeof(char)); if (!buf) return -1; numread = fread(buf, sizeof(char), fs, openFile); if (numread != fs) // do so...
... return -1; numread = fread(buf, sizeof(char), fs, openFile); if (numread != fs) // do something useful. // ... } if (buf) free(buf); The first line of the code calls QueryInterface on theFile, and if that succeeds assigns the new interface pointer to localFile. If the QueryInterface call fails, localFile will have a value of NULL. Note that the out parameter of the method
GetFileSize is a 64-bit integer. The type of this variable is PRInt64, but this type is not represented as a primitive on all platforms. On some platforms, PRInt64 is a struct with two fields - a high and a low 32-bit integer. So operations on this type must use special macros that do the right thing on each platform. On Windows or Linux, for example, it is possible to multiply a PRInt64 by a long like t...
DirectoryEntrySync - Web APIs
bandoned, having failed to reach any substantial traction. Basic concepts If you want to create subdirectories, you have to create each child directory in sequence. If you try to create a directory using a full path that includes parent directories that do not exist yet, you get an error. So create the hierarchy by recursively adding a new path after creating the parent directory. Example The
getFile() method returns a FileEntrySync, which represents a file in the file system. The following creates an empty file called seekrits.txt in the root directory. var fileEntry = fs.root.
getFile('seekrits.txt', {create: true}); The getDirectory() method returns a DirectoryEntrySync, which represents a file in the file system. The following creates a new directory called superseekrit in the root dir...
...ile('seekrits.txt', {create: true}); The getDirectory() method returns a DirectoryEntrySync, which represents a file in the file system. The following creates a new directory called superseekrit in the root directory. var dirEntry = fs.root.getDirectory('superseekrit', {create: true}); Method overview DirectoryReaderSync createReader () raises (FileException); FileEntrySync
getFile (in DOMString path, in optional Flags options) raises (FileException); DirectoryEntrySync getDirectory (in DOMString path, in optional Flags options) raises (FileException); void removeRecursively () raises (FileException); Methods createReader() Creates a new DirectoryReaderSync to read entries from this directory. DirectoryReaderSync createReader ( ) raises (FileExc...
...eException); Returns DirectoryReaderSync Represents a directory in a file system. Parameter None Exceptions This method can raise a FileException with the following codes: Exception Description NOT_FOUND_ERR The directory does not exist. SECURITY_ERR The browser determined that it was not safe to look up the metadata. [ todo: Explain why ]
getFile() Depending on how you've set the options parameter, the method either creates a file or looks up an existing file. void
getFile ( in DOMString path, in optional Flags options ) raises (FileException); Parameter path Either an absolute path or a relative path from the directory to the file to be looked up or created. You cannot create a file whose immediate parent does not exist. Create ...
... QUOTA_EXCEEDED_ERROR The operation would cause the application to exceed its storage quota. SECURITY_ERR The application does not have permission to access the element referred to by path. [ todo: Explain why ] TYPE_MISMATCH_ERR The path supplied exists, but it is not a directory. getDirectory() Creates or looks up a directory. The method is similar to
getFile() with DirectoryEntrySync being passed. void getDirectory ( in DOMString path, in optional Flags options ) raises (FileException); Parameter path Either an absolute path or a relative path from the directory to the file to be looked up or created. You cannot create a file whose immediate parent does not exist. Create the parent directory first. options An object literal describing the b...
Reading from Files - Archive of obsolete content
coding. In addition, lines may be read by reading the file up until a linefeed character is detected. A binary stream would be used to read bytes or numbers encoded within the file. To create an input stream, first get a reference to a nsIFile, and then use nsIScriptableIO.newInputStream() to open a stream for reading from it. To learn more about file objects, see Files and Streams. var file = IO.
getFile("Home", "sample.txt"); var stream = IO.newInputStream(file, "text"); This example first retrieves a file object using nsIScriptableIO.
getFile(). In this case, the file 'sample.txt' within the user's home directory is retrieved. Next, nsIScriptableIO.newInputStream() is called to create a new input stream for reading from the file. This method will open the file and return a stream. Naturally, if...
..., depending on their value. However, a number of other character encodings are available; see Reading Other Character Encodings below for details about reading text in other encodings. There are several methods available to read from an input stream. The two most common for text files are the readString and readLine methods for reading a string and a line from the file respectively. var file = IO.
getFile("Home", "sample.txt"); var stream = IO.newInputStream(file, "text"); var str = stream.readString(20); stream.close(); In this example, a text input stream is created for the file 'sample.txt'. The readString method is called to read a 20 character string from the file. Since the stream was just opened, the string will be read from the beginning of the file. A further read from the file will read...
...he string read from the stream. Usually this string have a length equal to the number of characters that were requested. However, it may not do, for instance if the end of the file was reached. This doesn't trigger an error, and the string will just be returned containing as many characters as are available. You can use the available method to check if data is available for reading: var file = IO.
getFile("Home", "sample.txt"); var stream = IO.newInputStream(file, "text"); var str = stream.readString(stream.available()); stream.close(); In this example, the available method is called to determine the number of available bytes for reading. Note that this method returns the number of bytes available, not the number of characters available, because the file hasn't been read and parsed yet, so the ac...
IO - Archive of obsolete content
textual data, Writing textual data, List of file-related error codes. Files and Streams This section describes how to access and get information about files, read from files and create and write files. Using Files A XUL application or extension may access files on disk, and either read or write to files. A file is accessed via a File object. To get a reference to a File object use nsIScriptableIO.
getFile(). The following example will retrieve a reference to a file located in the profile directory named sample.txt. var file = IO.
getFile("Profile", "sample.txt"); The nsIScriptableIO object is a global object always available within an application or extension. It provides a number of useful functions for dealing with files. Retrieve a File Object For information about getting a File Object, see A...
...w to delete a file, see Deleting a File. Open and Save Dialogs You can show a dialog to the user to allow them to select a file to open or enter a filename for saving. For details about this, see Open and Save Dialogs. File Errors See File Errors for a list of errors that might occur while using files. ...
...Specifically, to create a directory, see Creating Directories and to retrieve a list of files or subdirectories within a directory, see Iterating over the Files in a Directory. ...
nsIWebBrowserPersist
are identical to saveURI, with the exception of aIsPrivate which is used to indicate the private nature of the operation. ...
...adFile(httpLoc, sourceWindow) { try { //new obj_URI object var obj_URI = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(httpLoc, null, null); //new file object var obj_Tar
getFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); //set file with path obj_Tar
getFile.initWithPath("c:\\temp\\test.pdf"); //if file doesn't exist, create if(!obj_Tar
getFile.exists()) { obj_Tar
getFile.create(0x00,0644); } //new persistence object var obj_Persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist); // with persist flags if desired const nsIWBP = Co...
...sIWBP.PERSIST_FLAGS_FROM_CACHE; var privacyContext = sourceWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIWebNavigation) .QueryInterface(Components.interfaces.nsILoadContext); //save file to target obj_Persist.saveURI(obj_URI,null,null,null,null,obj_Tar
getFile,privacyContext); // Starting with Firefox 36 saveURI takes 8 parameters when called. aReferrerPolicy was added. // obj_Persist.saveURI(obj_URI,null,null,null,null,null,obj_Tar
getFile,privacyContext); } catch (e) { alert(e); } } See also nsICancelable ...
FileSystemDirectoryEntry.getDirectory() - Web APIs
is false. Values and results The table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. Option values File/directory condition Result create exclusive false n/a[1] Path exists and matches the desired type (depending on whether the function called is
getFile() or getDirectory() The successCallback is called with a FileSystemFileEntry if
getFile() was called or a FileSystemDirectoryEntry if getDirectory() was called. false n/a[1] Path exists but doesn't match the desired type The errorCallback is called with an appropriate error code (if the callback was provided). true false Path exists The existing file or dire...
.... Example In this example, a function is presented whose job it is to locate within a user's app data directory a JSON file containing a user dictionary for a specified language, then load that dictionary. ...
...SON.parse(reader.result); }); reader.readAsText(dictFile); }); }); }); } The loadDictionaryForLanguage() function starts by using getDirectory() to obtain the FileSystemDirectoryEntry object representing a subfolder named "Dictionaries" located inside the specified app data directory. The success callback for this takes the resulting directory entry object and calls
getFile() to get a FileSystemFileEntry object representing the dictionary file; the success callback for this, in turn, creates a new FileReader and uses it to load the contents of the file. When that is loaded successfully (as indicated by the loadend event being fired), the loaded text is passed into JSON.parse() to be reconstituted into a JavaScript object. Specifications Specification S...
File I/O - Archive of obsolete content
get a file object even if the specified file does not exist, and no exception will be thrown. An exception is thrown only when methods that require the file to exist are called, e.g., isDirectory(), moveTo(), and so on. Getting files in special directories Components.utils.import("resource://gre/modules/FileUtils.jsm"); // get the "data.txt" file in the profile directory var file = FileUtils.
getFile("ProfD", ["data.txt"]); Or the same without using FileUtils.jsm: // Get profile directory. var file = Components.classes["@mozilla.org/file/directory_service;1"]. getService(Components.interfaces.nsIProperties). get("ProfD", Components.interfaces.nsIFile); // Or using Services.jsm and Ci = Components.interfaces var file = Services.dirsvc.get("ProfD", Ci.nsIFile); // Appe...
..."); var dir = FileUtils.getDir("ProfD", ["DIR"], true); The above example creates a folder called "DIR" in the user's profile folder. You can also create a directory explicitly; for more information refer to nsIFile.create(). Creating temporary files To create a temporary file, use nsIFile.createUnique(): Components.utils.import("resource://gre/modules/FileUtils.jsm"); var file = FileUtils.
getFile("TmpD", ["suggestedName.tmp"]); file.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE); // do whatever you need to the created file alert(file.path); User input via nsIFilePicker The file picker component, nsIFilePicker, can be used to open standard Open / Save dialogs. It returns the user-specified file as nsIFile. nsIFile and path strings You can use nsIFil...
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
dow(win); // Hand over the application to xpcom/xul, this will block: appStartup.run(); Here is an example of a LocationProvider that works : public class LocationProvider implements IAppFileLocProvider { private final File libXULPath; int counter = 0; public LocationProvider(File grePath) { this.libXULPath = grePath; } public File
getFile(String aProp, boolean[] aPersistent) { File file = null; if (aProp.equals("GreD") || aProp.equals("GreComsD")) { file = libXULPath; if (aProp.equals("GreComsD")) { file = new File(file, "components"); } } else if (aProp.equals("MozBinD") || aProp.equals("CurProcD") || aProp.equals("ComsD") ...
...In order to communicate with XPCOM after this point, yo...
Writing to Files - Archive of obsolete content
IO.newOutputStream(). This method has a number of options to specify text or binary writing, the character set, and whether to append to an existing file or create a new one. To create an input stream, first get a reference to a nsIFile, and then use nsIScriptableIO.newOutputStream() to open a stream for writing to it. To learn more about file objects, see Files and Streams. try { var file = IO.
getFile("Desktop", "myinfo.txt"); var stream = IO.newOutputStream(file, "text"); } catch (ex) { alert(ex); } This example retrieves a file object on the desktop called 'myinfo.txt' using nsIScriptableIO.
getFile(). It doesn't matter whether the file exists or not. nsIScriptableIO.newOutputStream() is called to create a new output stream, which will be used to write to the file. In this example, the ope...
...greater than 128. This encoding is done automatically as long as you specify the 'text' flag to nsIScriptableIO.newOutputStream(). Other character encodings are available; see Writing Other Character Encodings below for details about writing text in other encodings. There are several methods available to write to a stream. For text files, you will usually use the writeString method. var file = IO.
getFile("Desktop", "myinfo.txt"); var stream = IO.newOutputStream(file, "text"); stream.writeString("This is some text"); stream.close(); In this example, a text input stream is created for the file 'myinfo.txt'. The writeString method is called to write a single string to the file, supplied as an argument to the method. Finally, the stream is closed by calling the stream's close method. You should ensu...
Audio for Web games - Game development
udioCtx = new AudioContext(); Now let's select all the <li> elements; later we can harness these elements to give us access to the track file path and each individual play button. const trackEls = document.querySelectorAll('li'); We want to make sure each file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function
getFile(filepath) { const response = await fetch(filepath); const arrayBuffer = await response.arrayBuffer(); const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer); return audioBuffer; } We can then use the await operator when calling this function, which ensures that we can run subsequent code when it has finished executing. Let's create another async function to set up the sample -...
...er; } We can then use the await operator when calling this function, which ensures that we can run subsequent code when it has finished executing. Let's create another async function to set up the sample -- we can combine the two async functions in a nice promise pattern to perform further actions when each file is loaded and buffered: async function loadFile(filePath) { const track = await
getFile(filePath); return track; } Let's also create a playTrack() function, which we can call once a file has been fetched. We need an offset here, so if we have started one file playing, we have a record of how far through to start another file. start() takes two optional parameters. The first is when to commence playback and the second is where, which is our offset. let offset = 0; function pla...
DownloadLastDir.jsm
ing the DownloadLastDir object To determine or set the path into which the last download occurred: // file is an nsIFile var file = DownloadLastDir.file; DownloadLastDir.file = file; You can also set and retrieve this information on a site-by-site basis. ...
... To determine or set the path into which the last download occurred: // file is an nsIFile var file = DownloadLastDir.file; DownloadLastDir.file = file; You can also set and retrieve this information on a site-by-site basis. To set the path, use setFile: // file is an nsIFile DownloadLastDir.setFile(uri, file); To retrieve the path in Firefox 26 or later, use
getFileAsync: DownloadLastDir.
getFileAsync(uri, function (file) { // file is an nsIFile console.log(file); }); Deprecated since Gecko 26.0 To retrieve the path in Firefox 25 or earlier, use
getFile: // file is an nsIFile var file = gDownloadLastDir.
getFile(uri); console.log(file); Private browsing mode When browsing normally, the browser uses the browser.download.lastDir preference to store the last download directory path. ...
FileUtils.jsm
ines dealing with files. ...
...x08 Corresponds to the PR_CREATE_FILE parameter to PR_OPEN MODE_APPEND 0x10 Corresponds to the PR_APPEND parameter to PR_OPEN MODE_TRUNCATE 0x20 Corresponds to the PR_TRUNCATE parameter to PR_OPEN PERMS_FILE 0644 Default permissions when creating files. PERMS_DIRECTORY 0755 Default permissions when creating directories Methods
getFile() Gets a file at the specified hierarchy under a nsIDirectoryService key. nsIFile
getFile( string key, array pathArray, bool followLinks ); Parameters key The nsIDirectoryService key to start from (see Getting special files for more info) pathArray An array of path components to locate beneath the directory specified by key. The last item in this array must be the leaf name of a f...
I/O Functions
aracter strings. Only the ASCII character set is supported. The forward slash (/) separates the directories in a pathname. NSPR converts the slashes in a pathname to the directory separator of the native OS--for example, backslash (\) on Windows and colon (:) on Mac OS--before passing it to the native system calls. Some file systems also differentiate drives or volumes. ...
... Only the ASCII character set is supported. The forward slash (/) separates the directories in a pathname. NSPR converts the slashes in a pathname to the directory separator of the native OS--for example, backslash (\) on Windows and colon (:) on Mac OS--before passing it to the native system calls. Some file systems also differentiate drives or volumes. ...
Index
This content is now available at nsIDirectoryService.registerProvider(). 553 unregisterProvider This content is now available at nsIDirectoryService.unregisterProvider(). 554 nsIDirectoryServiceProvider Directories, File I/O, Files, Interfaces, Interfaces:Scriptable, XPCOM, XPCOM Interface Reference nsIDirectoryServiceProvider. 555
getFile Mozilla, Reference, Reference(2), XPCOM, XPCOM API Reference, XPCOM Interface Reference Called by the Directory Service to obtain an nsIFile object corresponding for a given standard path location. 556 nsIDirectoryServiceProvider2 Directories, File I/O, Files, Interfaces, Interfaces:Scriptable, XPCOM, XPCOM Interface Reference The directory service calls this when i...
...ce Called by the Directory Service to obtain an nsIFile object corresponding for a given standard path location. 556 nsIDirectoryServiceProvider2 Directories, File I/O, Files, Interfaces, Interfaces:Scriptable, XPCOM, XPCOM Interface Reference The directory service calls this when it gets a request for a prop and the requested type is nsISimpleEnumerator. 557
getFiles XPCOM, XPCOM API Reference This method is called by the Directory Service to query an enumeration of file or directory locations. 558 nsIDiskCacheStreamInternal Interfaces, Interfaces:Scriptable, NeedsContent We use this method internally to close nsDiskCacheOutputStream under the cache service lock. 559 nsIDispatchSupport Interfaces, XPCOM, XPCOM In...
nsIDirectoryServiceProvider
xpcom/io/nsIDirectoryService.idlScriptable This interface is used by the Directory Service to get file locations. Inherits from: nsISupports Last changed in Gecko 1.7 nsIDirectoryServiceProvider. Method overview nsIFile
getFile(in string prop, out PRBool persistent); Methods
getFile() The Directory Service calls this method when it gets the first request for a prop or on every request if the prop is not persistent. nsIFile
getFile( in string prop, out PRBool persistent ); Parameters prop The symbolic name of the file. persistent true if the returned file will be cached by Directory Service. Subsequent requests for this prop will bypass the provider and use the cache. false if the provider will be asked for this prop each time it is requested. Return value The nsIFile ...
...code creates a global, read-only string called currDir with the value of the current working directory. __defineGetter__("currDir", function getCurrDir() { return Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.interfaces.nsIDirectoryServiceProvider) .
getFile("CurWorkD",{}).path; }); Test it with to see the magic happen. alert(currDir); See also nsDirectoryService nsIDirectoryService Additionally, see section 16.5.2 of the Rapid Application Development with Mozilla book for instructions on how to get the current working directory and the process binary directory, among other things. ...
nsIFileProtocolHandler
netwerk/protocol/file/nsIFileProtocolHandler.idlScriptable This interface provides methods to convert between nsIFile and nsIURI. It also provides access to Internet shortcuts stored on the host operating system's file system. Inherits from: nsIProtocolHandler Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Method overview nsIFile
getFileFromURLSpec(in AUTF8String url); AUTF8String getURLSpecFromActualFile(in nsIFile file); AUTF8String getURLSpecFromDir(in nsIFile file); AUTF8String getURLSpecFromFile(in nsIFile file); nsIURI newFileURI(in nsIFile aFile); nsIURI readURLFile(in nsIFile file); Methods
getFileFromURLSpec() Converts the URL string into the corresponding nsIFile if possible. A local fil...
... Return value A reference to a new nsIFile object. ...
nsIMsgIncomingServer
ce Gecko 1.8 void displayOfflineMsg(in nsIMsgWindow aWindow); boolean equals(in nsIMsgIncomingServer server); void forgetPassword(); void forgetSessionPassword(); AString generatePrettyNameForMigration(); boolean getBoolAttribute(in string name); boolean getBoolValue(in string attr); ACString getCharAttribute(in string name); ACString getCharValue(in string attr); nsILocalFile
getFileValue(in string relpref, in string abspref); nsIMsgFilterList getFilterList(in nsIMsgWindow aMsgWindow); long getIntAttribute(in string name); long getIntValue(in string attr); nsIMsgFolder getMsgFolderFromURI(in nsIMsgFolder aFolderResource, in ACString aURI); void getNewMessages(in nsIMsgFolder aFolder, in nsIMsgWindow aMsgWindow, in nsIUrlListener aUrlListener); ACString getPasswor...
...ng Description getCharAttribute() ACString getCharAttribute( in string name ); Parameters name Missing Description Return value Missing Description Exceptions thrown Missing Exception Missing Description getCharValue() ACString getCharValue( in string attr ); Parameters attr Missing Description Return value Missing Description Exceptions thrown Missing Exception Missing Description
getFileValue() nsILocalFile
getFileValue( in string relpref, in string abspref ); Parameters relpref Missing Description abspref Missing Description Return value Missing Description Exceptions thrown Missing Exception Missing Description getFilterList() nsIMsgFilterList getFilterList( in nsIMsgWindow aMsgWindow ); Parameters aMsgWindow Missing Description Return value Missing Description Ex...
BlobBuilder - Web APIs
Blob containing the data you sent into the blob builder. Note: The BlobBuilder interface has been deprecated in favor of the newly introduced Blob constructor. Method overview void append(in ArrayBuffer data); void append(in Blob data); void append(in String data, [optional] in String endings); Blob getBlob([optional] in DOMString contentType); File
getFile(in DOMString name, [optional] in DOMString contentType); Methods append() Appends the contents of the specified JavaScript object to the Blob being built. If the value you specify isn't a Blob, ArrayBuffer, or String, the value is coerced to a string before being appended to the blob. void append( in ArrayBuffer data ); void append( in Blob data ); void append( in String data, ...
...tentType Optional ); Parameters contentType Optional The MIME type of the data to be returned in the Blob. This will be the value of the Blob object's type property. Return value A Blob object containing all of the data passed to any calls to append() made since the BlobBuilder was created. This also resets the BlobBuilder so that the next call to append() is starting a new, empty blob.
getFile() Returns a File object. File
getFile( in DOMString name, [optional] in DOMString contentType ); Parameters name The file name. contentType Optional The MIME type of the data to be returned in the File. This will be the value of the File object's type property. Return value A File object. ...
FileSystemDirectoryEntry - Web APIs
interface, FileSystemEntry. Methods This interface inherits methods from its parent interface, FileSystemEntry. createReader() Creates a FileSystemDirectoryReader object which can be used to read the entries in this directory. getDirectory() Returns a FileSystemDirectoryEntry object representing a directory located at a given path, relative to the directory on which the method is called.
getFile() Returns a FileSystemFileEntry object representing a file located within the directory's hierarchy, given a path relative to the directory on which the method is called. Obsolete methods removeRecursively() Deletes a directory and all of its contents, including the contents of subdirectories. This has been removed from the spec. Specifications Specification Status Commen...
... Full support 50Notes Notes In Firefox, the errorCallback's input parameter is a DOMException rather than a FileError object.Opera Android No support NoSafari iOS Full support 11.3Samsung Internet Android Full support Yes
getFile ExperimentalChrome Full support 8Edge Full support 79Firefox Full support 50Notes Full support 50Notes Notes In Firefox, the errorCallback's input parameter is a DOMException rather than a FileError object.IE ...
FileSystemFlags.create - Web APIs
The create property on the FileSystemFlags dictionary is used to indicate whether or not the file should be created if it's missing. FileSystemFlags is only used when calling FileSystemDirectoryEntry.
getFile() or FileSystemDirectoryEntry.getDirectory(). Syntax fileSystemFlags.create = booleanValue Values The table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. ...
...create = booleanValue Values The table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. Option values File/directory condition Result create exclusive false n/a[1] Path exists and matches the desired type (depending on whether the function called is
getFile() or getDirectory() The successCallback is called with a FileSystemFileEntry if
getFile() was called or a FileSystemDirectoryEntry if getDirectory() was called. false n/a[1] Path exists but doesn't match the desired type The errorCallback is called with an appropriate error code (if the callback was provided). true false Path exists The existing file or dire...
FileSystemFlags.exclusive - Web APIs
The exclusive property on the FileSystemFlags dictionary is used in tandem with the create property to determine whether or not it's acceptable to require that the file not already exist when the reference to it is created by calling FileSystemDirectoryEntry.
getFile() or FileSystemDirectoryEntry.getDirectory(). ...
...lusive = booleanValue Values The table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. Option values File/directory condition Result create exclusive false n/a[1] Path exists and matches the desired type (depending on whether the function called is
getFile() or getDirectory() The successCallback is called with a FileSystemFileEntry if
getFile() was called or a FileSystemDirectoryEntry if getDirectory() was called. false n/a[1] Path exists but doesn't match the desired type The errorCallback is called with an appropriate error code (if the callback was provided). true false Path exists The existing file or dire...
FileHandle API - Web APIs
reading process: ' + this.error); } } File snapshot In many cases it can be handy to get a snapshot of the file. For example, there are many APIs that expect Blob or File objects such as FileReader (which can be easier to use to read the whole file) or XMLHttpRequest. ...
...Such an object is basically a DOMRequest with an extra power: it allows to monitor the progress of an operation. ...
Metadata.modificationTime - Web APIs
when the file system entry was last changed. Example This example tries to get a particular working file at tmp/workfile.json. Once that file has been found, its metadata is obtained and the file's modification timestamp year is compared to the current year. If it was last modified in a year at least five prior to the current year, the file is removed and a new one is created. ...
... If it was last modified in a year at least five prior to the current year, the file is removed and a new one is created. workingDirectory.
getFile("tmp/workfile.json", { create: true }, function(fileEntry) { fileEntry.getMetadata(function(metadata) { if ((new Date().getFullYear() - metadata.modificationTime.getFullYear()) >= 5) { fileEntry.remove(function() { workingDirectory.
getFile("tmp/workfile.json", { create: true }, function(newEntry) { fileEntry = newEntry; }); }); } }); }, handleError); This API has no official W3C or WHATWG specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and...
Advanced techniques: Creating and sequencing audio - Web APIs
one dial (DTMF) sounds, by playing a couple of oscillators together using the methods we've already looked at, however, in this section, we'll load in a sample file instead so we can take a look at what's involved. Loading the sample We want to make sure our file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function
getFile(audioContext, filepath) { const response = await fetch(filepath); const arrayBuffer = await response.arrayBuffer(); const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); return audioBuffer; } We can then use the await operator when calling this function, which ensures that we can only run subsequent code when it has finished executing. Let's create another async function ...
...erator when calling this function, which ensures that we can only run subsequent code when it has finished executing. Let's create another async function to set up the sample -- we can combine the two async functions in a nice promise pattern to perform further actions when this file is loaded and buffered: async function setupSample() { const filePath = 'dtmf.mp3'; const sample = await
getFile(audioCtx, filePath); return sample; } Note: You can easily modify the above function to take an array of files and loop over them to load more than one sample. This would be very handy for more complex instruments, or gaming. We can now use setupSample() like so: setupSample() .then((sample) => { // sample is our buffered file // ... }); When the sample is ready to p...
Getting File Information - Archive of obsolete content
, a 'file not found' exception will occur. You can catch this exception with a try-catch block, but it is better to use nsIFile.exists() to check first. This example will check if a file on the Desktop exists and set the variable 'filesize' to the size of the file. If the file is not present, the 'filesize' variable will not be changed from the default value of 0. var filesize = 0; var file = IO.
getFile("Desktop", "Saved File"); if (file.exists()) filesize = file.fileSize; It is also possible to modify the size of a file by setting the fileSize (nsIFile.Attributes) attribute to a value. This may be useful to truncate a file, however, setting the file size will also increase the size of a file if the value is larger than the current size of the file. In this case, the new part of the file wil...
Downloads.jsm
nloads. Properties Attribute Type Description Error Read only Constructor Constructor for a DownloadError object. When you catch an exception during a download, you can use this to verify if ex instanceof Downloads.Error, before reading the exception properties with the error details. Example (using Task.jsm): try { yield Downloads.fetch(sourceUri, tar
getFile); } catch (ex if ex instanceof Downloads.Error && ex.becauseTargetFailed) { console.log("Unable to write to the target file, ignoring the error."); } Methods createDownload() Creates a new Download object. Promise<Download> createDownload( Object aProperties ); Parameters aProperties Provides the initial properties for the newly created download. This matches the serializa...
PRFileInfo
Syntax #include <prio.h> struct PRFileInfo { PRFileType type; PRUint32 size; PRTime creationTime; PRTime modifyTime; }; typedef struct PRFileInfo PRFileInfo; Fields The structure has the following fields: type Type of file. See PRFileType. size Size, in bytes, of file's contents. creationTime Creation time per definition of PRTime. See prtime.h. modifyTime Last modification time per definition of PRTime. See prtime.h. ...
PRFileInfo64
Syntax #include <prio.h> struct PRFileInfo64 { PRFileType type; PRUint64 size; PRTime creationTime; PRTime modifyTime; }; typedef struct PRFileInfo64 PRFileInfo64; Fields The structure has the following fields: type Type of file. See PRFileType. size 64-bit size, in bytes, of file's contents. creationTime Creation time per definition of PRTime. See prtime.h. modifyTime Last modification time per definition of PRTime. See prtime.h. ...
PR_GetOpenFileInfo
ully obtained, PR_FAILURE. Description PR_GetOpenFileInfo obtains the file type (normal file, directory, or other), file size (as a 32-bit integer), and the file creation and modification times of the open file represented by the file descriptor. See Also For the 64-bit version of this function, see PR_GetOpenFileInfo64. To get equivalent information on a file that's not already open, use PR_
GetFileInfo. ...
nsLocalFile
<< XPCOM API Reference Summary A component implementing nsILocalFile. Class ID 2e23e220-60be-11d3-8c4a-000064657374 ContractID @mozilla.org/file/local;1 Supported Interfaces nsILocalFile, nsIFile Remarks This component should be accessed via the XPCOM Component Manager. Example Code function
getFileSize(path) { var file = Components.classes["@mozilla.org/file/local;1"]. createInstance(Components.interfaces.nsILocalFile); file.initWithPath(path); return file.fileSize; } See also Components, nsIComponentManager ...
nsIDirectoryServiceProvider2
xpcom/io/nsIDirectoryService.idlScriptable An extension of nsIDirectoryServiceProvider which allows multiple files to be returned for the given key. Inherits from: nsIDirectoryServiceProvider Last changed in Gecko 0.9.6 Method overview nsISimpleEnumerator
getFiles(in string prop); Methods
getFiles() The directory service calls this when it gets a request for a prop and the requested type is nsISimpleEnumerator. nsISimpleEnumerator
getFiles( in string prop ); Parameters prop The symbolic name of the file list. Return value An enumerator for a list of file locations. The elements in the enumeration are nsIFile. Use an XPCOM return code of NS_SUCCESS_AGGREGATE_RESULT if this result should be aggregated with other "lower" providers. If you are implementing this from JS, you...
nsIDownload
ce URI of the download. Read only. speed double The downloads transfer speed in bytes per second. Read only. startTime long long The time at which the transfer was started. Read only. state short The downloads current state. See nsIDownloadManager.Constants. Read only. target nsIURI The target of the transfer. Read only. tar
getFile nsILocalFile Indicates the location at which the downloaded file will be (or is, if the download is complete) stored. Read only. See also nsIDownloadManager nsIDownloadProgressListener nsIXPInstallManagerUI ...
nsIFile
non-superuser on the disk volume containing the nsIFile. Read only. fileSize PRInt64 The value of this attribute is the number of bytes corresponding to the data represented by the file. On the Mac, getting/setting the file size with nsIFile only deals with the size of the data fork. If you need to know the size of the combined data and resource forks use nsILocalFileMac.
GetFileSizeWithResFork(). Changing the size of a nsIFile operates on the underlying filesystem, possibly truncating the existing file to specified size. fileSizeOfLink PRInt64 This attribute exposes the size of the symbolic link referenced by this nsIFile. Unlike fileSize, this attribute corresponds to the size of the symbolic link referenced by this nsIFile. If this nsIFile ...
nsILocalFileMac
the display name of the application bundle (usually the human readable name of the application) Read only. bundleIdentifier AUTF8String Returns the identifier of the bundle. Read only. fileCreator OSType Native code only! fileSizeWithResFork PRInt64 Returns the combined size of both the data fork and the resource fork (if present) rather than just the size of the data fork as returned by
GetFileSize() Read only. fileType OSType File type and creator attributes. Native code only! Constants Constant Value Description CURRENT_PROCESS_CREATOR 0x8000000 Use with SetFileType() to specify the signature of current process. Obsolete since Gecko 2.0 Methods Native code only!getCFURL Note: Observes the state of the followLinks attribute. If the file object is an alias and followLinks i...
Storage
onnection - mozIStorageStatement. Bind parameters to a statement as necessary. Execute the statement. Check for errors. Reset the statement. ...
Getting Started Guide
ference. A given nsCOMPtr does not, however, cooperate in making other owning pointers. After learning how nsCOMPtr automatically AddRefs a pointer as it is being assigned in, the natural assumption is that it does the same thing when assigning out. Here is a snippet of code that demonstrates this misconception. // Incorrect assumptions about |nsCOMPtr|... nsresult nsCacheRecord::
GetFileSpec( nsIFileSpec** aFileSpec ) /* ...fills in the callers |nsFileSpec*| (which the caller supplied the address of) with a copy of my member variable |mFileSpec|, an |nsCOMPtr|. I.e., this function is a `getter'. Remember: good XPCOM getters always |AddRef| their result. */ { // ... *aFileSpec = mFileSpec; // the |nsCOMPtr| should take care of the ...
Using nsIDirectoryService
t is too high to set all of these properties at once, you can register to be a callback that can provide an nsIFile. To do this, you must get the implementation again like above. When you have it, QueryInterface for the nsIDirectoryService interface. Apart from this interface there is a function, registerProvider which will allow you to register a nsIDirectoryServiceProvider, which implements the
getFile callback function: var provider = {
getFile : function(prop, persistant) { // return an nsIFile }, } Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.interfaces.nsIDirectoryService).registerProvider(provider); When the callback is called, it will be passed the string key, and should return an nsIFile. The persistant flag allows you to specify if you want t...
FileException - Web APIs
errors. The added complexity of using WebWorkers with this API makes debugging even more challenging. To simplify things a bit, wrap your worker code in a try/catch. When errors occur, forward them to the main app using postMessage() as in the following: function onError(e) { postMEssage('ERROR:' + e.toString()); } try { //Error is thrown if "log.txt" already exists. var fileEntry = fs.root.
getFile('log.txt', {create: true, exclusive:true}0; } catch (e) { onErrror(e); } The sample code was borrowed from HTML5Rocks Attribute Attribute Type Description code unsigned short The most appropriate error code for the condition. Constants Note: Do not rely on the numeric values of the constants, which might change as the specifications continue to chan...
FileSystemEntry.copyTo() - Web APIs
rectory inside itself or one of its own child directories, or copying an item within the same directory without renaming it. FileError.QUOTA_EXCEEDED_ERR The operation exceeded the user's storage quota, or there isn't enough storage space left to complete the operation. Example This example shows how a temporary log file might be moved into a more permanent "log" directory. workingDirectory.
getFile("tmp/log.txt", {}, function(fileEntry) { workingDirectory.getDirectory("log", {}, function(dirEntry) { fileEntry.copyTo(dirEntry); }, handleError); }, handleError); Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
FileSystemEntry.fullPath - Web APIs
e to the root directory, with a "/" prepended to it to make it absolute. Syntax var fullPath = FileSystemEntry.fullPath; Value A USVString indicating the entry's full path. Example This example shows a function which is called with a file system; it then gets a FileSystemFileEntry for a file named data.json and returns its full path. function gotFileSystem(fs) { let path = ""; fs.root.
getFile("data.json", { create: true, exclusive: true }, function(entry) { path = fullPath; }, handleError(error)); return path; } Obviously, this is somewhat contrived, since we know that the file's full path is "/data.json", having just looked it up ourselves, but the concept holds up for scenarios in which you don't know it. Specifications Specification Status Comment ...
FileSystemEntry.getMetadata() - Web APIs
scribing what went wrong. Return value undefined. Errors FileError.NOT_FOUND_ERR The FileSystemEntry refers to an item which doesn't exist. FileError.SECURITY_ERR Security restrictions prohibit obtaining the requested metadata. Example This example checks the size of a log file in a temporary folder and, if it exceeds a megabyte, moves it into a different directory. workingDirectory.
getFile("tmp/log.txt", {}, function(fileEntry) { fileEntry.getMetadata(function(metadata) { if (metadata.size > 1048576) { workingDirectory.getDirectory("log", {}, function(dirEntry) { fileEntry.moveTo(dirEntry); }, handleError); } }); }, handleError); Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribut...
FileSystemEntry.moveTo() - Web APIs
own child directories, or copying an item within the same directory without renaming it. FileError.QUOTA_EXCEEDED_ERR The operation exceeded the user's storage quota, or there isn't enough storage space left to complete the operation. Example This example shows how a temporary log file might be moved into a more permanent "log" directory when it exceeds a megabyte in size. workingDirectory.
getFile("tmp/log.txt", {}, function(fileEntry) { fileEntry.getMetadata(function(metadata) { if (metadata.size > 1048576) { workingDirectory.getDirectory("log", {}, function(dirEntry) { fileEntry.moveTo(dirEntry); }, handleError); } }); }, handleError); Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribut...
FileSystemEntry.remove() - Web APIs
DIFICATION_ALLOWED_ERR The file system's state doesn't permit removing the file or directory. FileError.NOT_FOUND_ERR The file or directory doesn't exist. FileError.SECURITY_ERR The entry couldn't be removed due to permissions or other access constraints, or because there are too many calls being made on file resources. Example This example deletes a temporary work file. workingDirectory.
getFile("tmp/workfile.json", {}, function(fileEntry) { fileEntry.remove(function() { /* the file was removed successfully */ }); }, handleError); Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFire...
FileSystemEntry - Web APIs
see an example of how toURL() works, see the method description. The snippet below shows you how you can remove a file by name. // Taking care of the browser-specific prefixes. window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; ... // Opening a file system with temporary storage window.requestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, function(fs) { fs.root.
getFile('log.txt', {}, function(fileEntry) { fileEntry.remove(function() { console.log('File removed.'); }, onError); }, onError); }, onError); Properties This interface provides the following properties. filesystem Read only A FileSystem object representing the file system in which the entry is located. fullPath Read only A USVString object which provides the full, absolute ...
FileSystemFileEntry - Web APIs
alling file(). Example The following code creates an empty file called "log.txt" (if it doesn't exist) and fills it with the text "Meow". Inside the success callback, event handlers are set up to handle the error error and writeend events. The text data is written to the file by creating a blob, appending text to it, and passing the blob to FileWriter.write(). function onInitFs(fs) { fs.root.
getFile('log.txt', {create: true}, function(fileEntry) { // Create a FileWriter object for our FileSystemFileEntry (log.txt). fileEntry.createWriter(function(fileWriter) { fileWriter.onwriteend = function(e) { console.log('Write completed.'); }; fileWriter.onerror = function(e) { console.log('Write failed: ' + e.toString()); }; // Create a new Blob...
FileSystemFlags - Web APIs
is false. Values and results The table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. Option values File/directory condition Result create exclusive false n/a[1] Path exists and matches the desired type (depending on whether the function called is
getFile() or getDirectory() The successCallback is called with a FileSystemFileEntry if
getFile() was called or a FileSystemDirectoryEntry if getDirectory() was called. false n/a[1] Path exists but doesn't match the desired type The errorCallback is called with an appropriate error code (if the callback was provided). true false Path exists The existing file or dire...