fs module

The fs module provides APIs to access the file system.

  • You can read files in the local:, store:, and temporary: directories.
  • You can write files to the temporary: directory.

All APIs in the fs module are asynchronous, except fs.temporary(). If two transactions are writing to the same file, the contents of the file are what the last transaction wrote.

To access APIs in the fs module, use the require('fs') statement.

Several APIs use the options parameter. The options parameters refer to a JSON object that contains options specifications. The options file contains entries that are related to the method.
fsOptions = {
  old_path:string,  /* for rename */
  new_path:string,  /* for rename */
       TTL:number,  /* for various, number can be 0-86400 */
      file:string,  /* for read/write */
  encoding:string,  /* ascii, utf8, ucs2, utf16le, base64, base64url, or hex */
      data:various  /* for write */
}

The file label specifies the full path and name specification for the file. The data label specifies the contents for the method. The time to live (TTL) is provided primarily for efficient space management. The old_path and new_path labels provide file specifications for the rename function. The TTL label specifies an integer in the range 0 - 86400 that defines the time to live in seconds for the created temporary file. The default value is 10 seconds. The TTL is only valid for the temporary: directory. The encoding label specifies an encoding to apply to a buffer. The data label specifies data to write or append.

When the TTL expires, the file is deleted automatically. When TTL is 0, the time to live does not expire; that is, the file is permanent. If you append to an existing file, the TTL is reset to a newly specified TTL or the default value if not specified.

For example,
var myFile = "store:///myfile.txt";
var options = { file : myFile, data : "Goodbye, World." };

The callback parameter is more fully described in the urlopen() method. Most callback functions have one error object that represents any error that is generated during the process. The readAsFile, readAsJSON, and readAsXML functions have both an error object and a data object.

The supported encoding values are ascii, utf8, ucs2, utf16le, base64, base64url, and hex. Encoding is fully described in the buffers object.

If an error occurs in these APIs, an exception is raised.

fs.appendFile()

Adds data to the end of a file.

Syntax
fs.appendFile(file,data,callback)
fs.appendFile(options,callback)
Parameters
file
A string that contains the fully specified location of the file that includes the containing directories.
data
A string or object in a buffer to be added to the end of the file.
callback
The callback processes the response from the server. For more information, see urlopen module.
options
A JSON object that provides the file, data, TTL for the append operation.
Example
  • Specify a string or an object to append to the end of a file.
    var mybuff = "Hello, World.";
    fs.appendFile("temporary:///my_file", mybuff, function(appendError){
      if (appendError) {
        // error return.
        } else {
          // append worked.
      }
    });
  • Append data by using a variable file.
    var fn = "temporary:///my_file";
    var myText = "Hello, world.";
    var appendOptions = { file : fn , data : mytext };
    fs.appendFile(appendOptions, function(appendError) {
      if (appendError) {
        // something bad happened - - error
        } else {
          // append worked
      }
    });

fs.exists()

Returns a Boolean value that is true when the file exists and false otherwise.

Syntax
fs.exists(file,callback)
Parameters
file
A string that contains the fully specified location of the file.
callback
The callback processes the response from the server. For more information, see urlopen module.
Example
Check that a file exists before it is read.
fs.exists("temporary:///my_file", function(exists){
if(exists) {
  fs.readFile("temporary:///my_file",function(readError,readData)
   if (error) {
     // handle the readFile error
   } else {
     console.log('Data read:'+data+"\n");
   }
  });
});

fs.readFile()

Reads a specified file and returns the file contents.

Syntax
fs.readFile(file,callback)
fs.readFile(options,callback)
Parameters
file
A string that contains the fully specified location of the file.
callback
The callback processes the response from the server. The callback has one error object that represents any error that is generated during the rename process and one string buffer object that represents the read data options. For example, function(error,data). For more information, see urlopen module.
options
A JSON object that contains the values for file and encoding.
{
  file:"file specification",
  encoding:"encoding"
}
Encoding is applied to the raw buffer. If an encoding is not specified, the raw buffer is returned.
Example
Read a buffer load.
fs.readFile("temporary:///my_file",function(error,data) {
  if(error) {
    // Handle error.
  } else {
    // No error. Proceed with data in raw form.
    console.log('Data read:'+data+"\n");
  }
});

fs.readAsJSON()

Reads a specified file in JSON format and returns the file contents.

Syntax
fs.readAsJSON(file,callback)
Parameters
file
A string that contains the fully specified location of the file.
callback
The callback processes the response from the server. The callback function has both an error object and a data object. For more information, see urlopen module.
Example
Read a buffer as a JSON object.
fs.readAsJSON("store:///data_file",function(error,data) {
  if (error) {
    // Handle the error.
  } else {
    // No error. Process the data.
    console.log('Data read:'+data+"\n");
  }
});

fs.readAsXML()

Reads a specified file in XML format and returns the file contents.

Syntax
fs.readAsXML(file,callback)
Parameters
file
A string that contains the fully specified location of the file.
callback
The callback processes the response from the server. The callback function has both an error object and a data object. For more information, see urlopen module.
Example
Read a buffer as an XML object.
fs.readAsXML("store:///data_file",function(error,data) {
  if (error) {
    // Handle the error.
  } else {
    // No error.  Process the data.
    var buffer = data;
  }
});

fs.rename()

Renames a file in the temporary: directory. The specified TTL or the default is applied.

Syntax
fs.rename(old,new,callback)
fs.rename(options,callback)
Parameters
old
A string that contains the fully specified name of the file to rename.
new
A string that contains the fully specified name of the renamed file.
callback
The callback processes the response from the server. The callback function has an error object. For more information, see urlopen module.
options
A JSON object that contains the values for the file specifications and TTL.
Example
Rename a file in the temporary: directory from data_file to my_file.
fs.rename("temporary:///data_file","temporary:///my_file",function(error){
  if(error) {
    // Handle error.
  } else {
    // No error. Rename complete.
  }
});

fs.temporary()

Creates a temporary file for use in the temporary: directory, and returns its fully specified name.

Syntax
fs.temporary()
Guidelines
The format of the temporary file is temporary:///temp_serial, where serial is a 5-digit serial number.
Get a file in the temporary: directory.
var temp_file = fs.temporary();

The name is created for temporary use but no file activity occurs. To create an empty file, use fs.writeFile().

fs.truncate()

Truncates the file to a specified length.

Syntax
fs.truncate(file,size,callback)
Parameters
file
A string that contains the fully specified name of the file to truncate.
size
An integer that specifies the length of the file that is being truncated. If set to 0, the entire contents of the file are removed.
callback
The callback processes the response from the server. For more information, see urlopen module.

fs.writeFile()

Writes a file.

Syntax
fs.writeFile(file,data,callback)
fs.writeFile(options,callback)
Parameters
file
A string that contains the fully specified file name in the temporary: directory.
data
The text to write to the file.
callback
The callback processes the response from the server. the callback function has one error object that represents any error that is generated during the process. For more information, see urlopen module.
options
A JSON object that contains the values for file, data, and TTL.
Examples
  • Write the buf buffer to a temporary file data_file.
    fs.writeFile("temporary:///data_file", buf, callback);
  • Use an options specification to write the buf buffer to a temporary file with 15 seconds to live. Append an empty buffer to the temporary file and adjust the TTL to back 10 seconds.
    var fs = require('fs');
    var temp_file = fs.temporary();
    var buf = new Buffer("hello, world");
    var emptybuffer = "";
    var options = {'file': temp_file,'data': buf, 'TTL': 15};
    
    fs.writeFile(options, function(error) { 
      if(error) {
        console.error(error);
      } else {
        fs.appendFile(temp_file, emptybuffer, function(error) {
          if(error){
            console.error(error);
          } else {
            console.log('appendFile success.');
          }
        });
      }
    });