The Mozilla
Organization
Our Mission
Who We Are
Getting Involved
Community
Editorials
What's New
Development
Roadmap
Module Owners
Blue Sky
Projects
Status
Tools
Products
Source Code
Binaries
Documentation
License Terms
Bug Reports
Search
Feedback


JavaScript File object proposal
by Henri Tourgemaine
and Michael Ang <mang@netscape.com>

This documents describes a proposed API for the JavaScript File object. A lot of the API has been implemented (but not tested), and there is work yet to be done. Please send comments to mang@netscape.com.

Many scripts in JavaScript require I/O capabilities and particularly access to normal files. This document describes such a File object that can be implemented by host implementations. The immediate goal is to provide normal file access, and later add Perl-like filehandle features. The design of the File object should allow these features to be added later on.

The interface is a mix of the Server Side JS File object, the Java File object and tries to follow existing implicit JavaScript usage ( readln instead of readLine, for example ).

The File object gives 2 way to access the data inside a file: a text oriented access, based on characters, and a binary oriented access, based on bytes. No provision for different encodings is provided.


1.0 Filenames

    Filenames are specified as strings that have an implementation defined format. Use of standard "file:" URLs is encouraged.

    Examples of possible prefix strings are "/" to indicate the Unix root directory, "c:" to specify a Windows drive letter, and "file:" to indicate a file URL.

    Eventually we want to be able to do things like this:

      var mail = new File("|/usr/bin/mail foo@bar.com");
      mail.writeln("I love JavaScript.");
      mail.close();

    It should be possible to do this using the current API since filenames are platform dependent.


2.0 Properties of the File constructor

    in a File object that represents the standard input.
    out a File object that represents the standard output.
    err a File object that represents the standard error.
    currentDir a File object referring to the current directory.
    separator the system name separator.

2.1 Properties of File instances

    length contains the number of characters in the file.
    parent contains the directory containing the file.
    path contains the canonical path to the file.
    name contains the name of the file.
    isDirectory true if the file is a directory.
    isFile true if the file is a normal file
    exists true if the file exists.
    canRead true if the file can be read.
    canWrite true if the file can be written.
    opened true if the file has been successfully opened.
    type contains a string specifying the type of data or encoding contained in the file.
    mode contains a string of comma separated value specifying the way this file has been opened.
    lastModified contains a Date object for the time the file was last modified.
    randomAccess contains a flag indicating if the "position" property can be used.
    position contains the current offset in the file. this is the only property that may be set.

2.2 Instance methods


3.0 Properties of the File constructor

    in

    A File object that represents the standard input.

    out

    A File object that represents the standard input.

    err

    A File object that represents the standard input.

    currentDir

    This property contains a File object pointing to the current directory.

    separator

    The system name separator. For example, "/" on Unix.

3.1 Properties of File instances

    length

    This property contains the number of characters in the file.

    parent

    This property contains a File object pointing to the directory containing the file.
    If the file isn't contained in anything (root directory), the property contains the file itself.

    path

    This property contains the canonical path to the file.

    name

    This property contains the name of the file.

    isDirectory

    This property contains true if the file is a directory.

    isFile

    This property contains true if the file is a regular data file. Note that on some platforms, both "isDirectory" and "isFile" may return false for some special type of files (for example, unix named pipes).

    exists

    This property equals true if the file exists.

    canRead

    This property contains true if the file can be read.

    canWrite

    This property contains true if the file can be written.

    opened

    This property contains true if the file has been successfully opened and is still open.

    type

    This property contains a string specifying the type of data or encoding used when the file was opened.
    The value can be "text", "binary", or a specific text encoding.

    mode

    This property contains a string of comma separated value specifying the way this file is opened.
    The values can be "read", "write", "randomAccess", "append", "autoflush", "replace"

    lastModified

    This property contains a Date object for the time the file was last modified.

    randomAccess

    This property contains a flag indicating that the file is being opened in random access mode.
    This means the "position" property can be read and set.

    position

    This property contains the current offset in the file. this is the only property that may be set. This property has no meaning if the file is not in "randomAccess" mode.

3.1.1 Special properties for directories

    A File object that represents a directory gets additional properties that represent the files contained in the directory.

    These properties have the same names as the files in the directory.

    Example
    myDir = new File("some/directory");
    myFileInDir = myDir.foo;

    Named property lookup can be used to refer to files whose names are not valid as normal property names.

    mySameFileInDir = myDir["foo"];
    myOtherFile = myDir["some long filename with spaces and such"];

3.2 Instance methods

    open(type,mode)

    If no mode is specified, the default mode is "read,append,create". If no type is specified, the default type is "text".

    Valid modes (can be combined)
    read specify that the file is opened for reading.
    write specify that the file is opened for writing.
    randomAccess specify that the file is opened for both reading and writing.
    append position the file pointer at the end of the file.
    autoflush ask to automatically flush the output when a newline character is written.
    replace erase the content of the file before opening it.
      Notes:
      • if both "read" and "write" are set, then "randomAccess" is automatically set.
      • if "randomAccess" is set, then the mode is automatically set to "binary".
      • if "append", "replace" or "autoflush" are set without "write" nor "randomAccess", they are ignored.

    Valid types
    text open the file for text access, using the default file encoding.
    binary open the file for binary access.
    any other string open the file for text access, using the given type as the encoding.

    close()

    This method closes the file.

    delete(recursive)

    This method deletes the file or removes the directory given as argument. Normally if remove is called on a directory it is only deleted if the directory is empty. If the optional recursive parameter is true, then the directory is always deleted, including any subdirectories.

    copyTo(filename)

    This method tries to make a raw copy of the source file into a destination file.
    It will fail if the source file doesn't exist, or is a directory.

    moveTo(filename)

    This method moves/renames the file.

    flush()

    This method forces to flush the output buffers of the file.
    It should be used only on files open for output without the "autoflush" option.

    skip(numChars)

    This methods skips the next numChars characters or bytes depending on the current access mode for the file.

    read(numChars)

    This method reads numChars characters and return them in a string. If there are less than numChars characters left to read, then the available characters are returned. If the file is at EOF, then null is returned.

    readln()

    This methods reads characters until an end of line/file is encountered then returns the string for these characters (without any end of line character).

    readAll()

    This methods reads the rest of the file and returns an array with a slot for each line of the file.

    write(arg0,arg1,...,argn)

    This method converts each arguments into a string, then writes it to the file (without separators).

    writeln(arg0,arg1,...,argn)

    This method is similar to write, but adds a platform dependent end of line after outputting the last argument.

    writeAll(Array)

    This method takes an array as an argument, and calls writeln() on each of them

    list(filter)

    This method returns an array. if the file is a directory, an slot is created for each file inside that directory, and a property with the file name is created too. Both point to a File object referring to the file.

    filter is an optional argument that should be a function or a regular expression, and is used to filter the array. If the argument is a regular expression, the array will only contain files for which the pattern matches. If the argument is a function, the array will only contain files for which the function returned true when called with the file name as argument.

    Example
    File.currentDir.list( function (name) { return name.length==3; } );

    Returns only files in the current directory whose names are 3 characters long.

    mkdir(makeParents)

    This method attempts to create a directory.

    If makeParents is not specified or is false, then no parent directories will be created. If makeParents is true, then parent directories will be created as necessary.

    toString()

    This method returns the canonical path to the file.

    toURL()

    return the name of the file as a "file:" URL


4.0 I want to play

    Flaming disclaimer: Do not play with the File object if you are not prepared to have your hard drive erased, smashed, and broken into little bits! It mostly works right now, but no guarantees.

    Currently the File object can be built into the core JS engine using a define. This is wrong. Once XPCOM settles down, the File object should be COM-ified.

    To play with/hack on the File object, get the latest and greatest (usually) JavaScript using CVS:

    cvs co -rSpiderMonkeyDev_BRANCH mozilla/js/src

    Be warned that this gives you the active development branch for JavaScript, which offers few guarantees of stability.

    To build (the reference interpreter on UNIX in this example) with the File object define JS_HAS_FILE_OBJECT while building. You also need to build against NSPR which you can do by defining JS_THREADSAFE.

    cd mozilla/js/src
    setenv JS_THREADSAFE 1
    setenv JS_HAS_FILE_OBJECT 1
    gmake -f Makefile.ref
    ./js

5.0 Unresolved questions/TODO

    Exceptions should be generated when errors occur. What should the format of these be? Need to mark these errors.

    Should there be event handlers?

    XPCOM-ify.


Mike Ang
Last modified: Fri Dec 4 18:07:47 PST 1998



Copyright © 1998 The Mozilla Organization.