Module fs
This module provides a file system API for the manipulation of paths, directories, files, links, and the construction of input and output streams. It follows the CommonJS Filesystem/A proposal.
Some file system manipulations use a wrapper around standard POSIX functions. Their
functionality depends on the concrete file system and operating system. Others use
the java.io
package and work cross-platform.
Functions
- absolute(path)
- base(path, ext)
- canonical(path)
- changeGroup(path, group)
- changeOwner(path, owner)
- changePermissions(path, permissions)
- changeWorkingDirectory(path)
- copy(from, to)
- copyTree(from, to)
- directory(path)
- exists(path)
- extension(path)
- group(path)
- hardLink(source, target)
- isAbsolute(path)
- isDirectory(path)
- isFile(path)
- isLink(path)
- isReadable(path)
- isRelative(path)
- isWritable(path)
- iterate(path)
- join()
- lastModified(path)
- list(path)
- listDirectoryTree(path)
- listTree(path)
- makeDirectory(path, permissions)
- makeTree(path)
- move(source, target)
- normal(path)
- open(path, options)
- openRaw(path, options)
- owner(path)
- path()
- permissions(path)
- read(path, options)
- readLink(path)
- relative(source, target)
- remove(path)
- removeDirectory(path)
- removeTree(path)
- resolve(paths...)
- same(pathA, pathB)
- sameFilesystem(pathA, pathB)
- size(path)
- split(path)
- symbolicLink(source, target)
- touch(path, mtime)
- workingDirectory()
- write(path, content, options)
Class Path
Instance Methods
Path ()
Path constructor. Path is a chainable shorthand for working with paths.
Path.prototype. from (target)
Return the relative path from the given source path to this path. Equivalent
to fs.Path(fs.relative(source, this))
.
Parameters
null | target |
Path.prototype. join ()
Join a list of paths to this path.
Path.prototype. listPaths ()
Return the names of all files in this path, in lexically sorted order and wrapped in Path objects.
Path.prototype. resolve ()
Resolve against this path.
Path.prototype. to (target)
Return the relative path from this path to the given target path. Equivalent
to fs.Path(fs.relative(this, target))
.
Parameters
null | target |
Path.prototype. toString ()
Path.prototype. valueOf ()
This is a non-standard extension, not part of CommonJS Filesystem/A.
Permissions (permissions, constructor)
The Permissions class describes the permissions associated with a file.
Parameters
Number|Object | permissions | a number or object representing the permissions. |
null | constructor |
Permissions.prototype. toNumber ()
absolute (path)
Make the given path absolute by resolving it against the current working directory.
Example
>> fs.absolute('foo/bar/test.txt');
'/Users/username/Desktop/working-directory/foo/bar/test.txt'
Parameters
null | path | the path to resolve |
Returns
String | the absolute path |
base (path, ext)
Return the basename of the given path. That is the path with any leading directory components removed. If specified, also remove a trailing extension.
Example
>> fs.base('/a/b/c/foosomeext', 'someext');
'foo'
Parameters
String | path | the full path |
String | ext | an optional extension to remove |
Returns
String | the basename |
canonical (path)
Returns the canonical path to a given abstract path. Canonical paths are both absolute and intrinsic, such that all paths that refer to a given file (whether it exists or not) have the same corresponding canonical path.
Parameters
String | path | a file path |
Returns
String | the canonical path |
changeGroup (path, group)
Changes the group of the specified file. This function wraps the
POSIX chown()
function. Supports group name string
as well as gid number input.
Parameters
String | path | |
String|Number | group | group name string or gid number |
See
changeOwner (path, owner)
Changes the owner of the specified file. This function wraps the
POSIX chown()
function. Supports user name string as well
as uid number input.
Parameters
String | path | |
String|Number | owner | the user name string or uid number |
See
changePermissions (path, permissions)
Changes the permissions of the specified file. This function wraps the
POSIX chmod()
function.
Parameters
String | path | |
Number|Object | permissions |
See
changeWorkingDirectory (path)
Set the current working directory to path
.
Parameters
String | path | the new working directory |
copy (from, to)
Read data from one file and write it into another using binary mode.
Example
// Copies file from a temporary upload directory into /var/www
fs.copy('/tmp/uploads/fileA.txt', '/var/www/fileA.txt');
Parameters
String | from | original file |
String | to | copy to create |
copyTree (from, to)
Copy files from a source path to a target path. Files of the below the source path are copied to the corresponding locations relative to the target path, symbolic links to directories are copied but not traversed into.
Example
Before:
└── foo
├── bar
│ └── example.m4a
└── baz
// Copy foo
fs.copyTree('./foo', './foo2');
After:
├── foo
│ ├── bar
│ │ └── example.m4a
│ └── baz
└── foo2
├── bar
│ └── example.m4a
└── baz
Parameters
String | from | the original tree |
String | to | the destination for the copy |
directory (path)
Return the dirname of the given path. That is the path with any trailing non-directory component removed.
Example
>> fs.directory('/Users/username/Desktop/example/test.txt');
'/Users/username/Desktop/example'
Parameters
String | path |
Returns
String | the parent directory path |
exists (path)
Return true if the file denoted by path
exists, false otherwise.
Parameters
String | path | the file path. |
extension (path)
Return the extension of a given path. That is everything after the last dot in the basename of the given path, including the last dot. Returns an empty string if no valid extension exists.
Example
>> fs.extension('test.txt');
'.txt'
Parameters
String | path |
Returns
String | the file's extension |
hardLink (source, target)
Creates a hard link at the target path that refers to the source path. The concrete implementation depends on the file system and the operating system.
This function wraps the POSIX link()
function, which may not work
on Microsoft Windows platforms.
Parameters
String | source | the source file |
String | target | the target file |
See
isAbsolute (path)
Check whether the given pathname is absolute. This is a non-standard extension, not part of CommonJS Filesystem/A.
Example
>> fs.isAbsolute('../../');
false
>> fs.isAbsolute('/Users/username/Desktop/example.txt');
true
Parameters
null | path | the path to check |
Returns
Boolean | true if path is absolute, false if not |
isDirectory (path)
Returns true if the file specified by path exists and is a directory.
Parameters
String | path | the file path |
Returns
Boolean | whether the file exists and is a directory |
isFile (path)
Returns true if the file specified by path exists and is a regular file.
Parameters
String | path | the file path |
Returns
Boolean | whether the file exists and is a file |
isLink (path)
Return true if target file is a symbolic link, false otherwise.
This function wraps the POSIX lstat()
function to get the
symbolic link status.
Parameters
String | path | the file path |
Returns
Boolean | true if the given file exists and is a symbolic link |
See
isReadable (path)
Returns true if the file specified by path exists and can be opened for reading.
Parameters
String | path | the file path |
Returns
Boolean | whether the file exists and is readable |
isRelative (path)
Check whether the given pathname is relative (i.e. not absolute). This is a non-standard extension, not part of CommonJS Filesystem/A.
Parameters
null | path | the path to check |
Returns
Boolean | true if path is relative, false if not |
isWritable (path)
Returns true if the file specified by path exists and can be opened for writing.
Parameters
String | path | the file path |
Returns
Boolean | whether the file exists and is writable |
iterate (path)
Returns a generator that produces the file names of a directory.
Parameters
String | path | a directory path |
join ()
Join a list of paths using the local file system's path separator.
The result is not normalized, so join("..", "foo")
returns "../foo"
.
lastModified (path)
Returns the time a file was last modified as a Date object.
Parameters
String | path | the file path |
Returns
Date | the date the file was last modified |
list (path)
Returns an array with all the names of files contained in the direcory path
.
Parameters
String | path | the directory path |
Returns
Array | a list of file names |
listDirectoryTree (path)
Return an array with all directories below (and including) the given path, as discovered by depth-first traversal. Entries are in lexically sorted order within directories. Symbolic links to directories are not traversed into.
Example
// File system tree of the current working directory:
.
└── foo
└── bar
└── baz
fs.listDirectoryTree('.');
// returned array:
[ '', 'foo', 'foo/bar', 'foo/bar/baz' ]
Parameters
null | path | the path to discover |
Returns
Array | array of strings with all directories lexically sorted |
listTree (path)
Return an array with all paths (files, directories, etc.) below (and including) the given path, as discovered by depth-first traversal. Entries are in lexically sorted order within directories. Symbolic links to directories are returned but not traversed into.
Example
// File system tree of the current working directory:
.
├── foo
│ └── bar
│ └── baz
├── musicfile.m4a
└── test.txt
fs.listTree('.');
// returned array:
['', 'foo', 'foo/bar', 'foo/bar/baz', 'musicfile.m4a', 'test.txt']
Parameters
null | path | the path to list |
Returns
Array | array of strings with all discovered paths |
makeDirectory (path, permissions)
Create a single directory specified by path
. If the directory cannot be
created for any reason an error is thrown. This includes if the parent
directories of path
are not present. If a permissions
argument is passed
to this function it is used to create a Permissions instance which is
applied to the given path during directory creation.
This function wraps the POSIX mkdir()
function.
Parameters
String | path | the file path |
Number|Object | permissions | optional permissions |
See
makeTree (path)
Create the directory specified by path
including any missing parent
directories.
Example
Before:
└── foo
fs.makeTree('foo/bar/baz/');
After:
└── foo
└── bar
└── baz
Parameters
null | path | the path of the tree to create |
move (source, target)
Move a file from source
to target
.
Example
// Moves file from a temporary upload directory into /var/www
fs.move('/tmp/uploads/fileA.txt', '/var/www/fileA.txt');
Parameters
String | source | the source path |
String | target | the target path |
Throws
normal (path)
Normalize a path by removing '.' and simplifying '..' components, wherever possible.
Example
>> fs.normal('../redundant/../foo/./bar.txt');
'../foo/bar.txt'
Parameters
null | path |
Returns
String | the normalized path |
open (path, options)
Open the file corresponding to path
for reading or writing,
depending on the options
argument. Returns a [binary stream][io#Stream]
or a [text stream][io#TextStream].
The options
argument may contain the following properties:
- read (boolean) open the file in read-only mode.
- write (boolean) open the file in write mode starting at the beginning of the file.
- append (boolean) open the file in write mode starting at the end of the file.
- binary (boolean) open the file in binary mode.
- charset (string) open the file in text mode using the given encoding. Defaults to UTF-8.
Instead of an options
object, a string with the following modes can be
provided:
- r (string) equivalent to read-only
- w (string) equivalent to write
- a (string) equivalent to append
- b (string) equivalent to binary
So an options
object { read: true, binary: true }
and the mode string 'rb'
are
functionally equivalent. Note: The options canonical and exclusive proposed by CommonJS are
not supported.
Example
// Opens a m4a file in binary mode
var m4aStream = fs.open('music.m4a', {
binary: true,
read: true
});
// The equivalent call with options as string
var m4aStream = fs.open('music.m4a', 'br');
// Opens a text file
var textStream = fs.open('example.txt', { read: true });
// The equivalent call with options as string
var textStream = fs.open('example.txt', 'r');
Parameters
String | path | the file path |
Object|String | options | options as object properties or as mode string |
Returns
Stream|TextStream | a |
openRaw (path, options)
Opens the file corresponding to path
for reading or writing in binary
mode. The options
argument may contain the following properties:
- read (boolean) open the file in read-only mode. (default)
- write (boolean) open the file in write mode starting at the beginning of the file.
- append (boolean) open the file in write mode starting at the end of the file.
Parameters
String | path | the file path |
Object | options | options |
Returns
Stream |
See
path ()
A shorthand for creating a new Path
without the new
keyword.
read (path, options)
Read the content of the file corresponding to path
. Returns a
String or [ByteString][binary#ByteString] object depending on the options
argument. This function supports the same options as [open()][#open].
Parameters
String | path | the file path |
Object | options | optional options |
Returns
String|Binary | the content of the file |
readLink (path)
Returns the immediate target of the symbolic link at the given path
.
This function wraps the POSIX readlink()
function, which may not work
on Microsoft Windows platforms.
Parameters
String | path | a file path |
See
relative (source, target)
Establish the relative path that links source to target by strictly traversing up ('..') to find a common ancestor of both paths. If the target is omitted, returns the path to the source from the current working directory.
Example
>> fs.relative('foo/bar/', 'foo/baz/');
'../baz/'
>> fs.relative('foo/bar/', 'foo/bar/baz/');
'baz/'
Parameters
String | source | |
String | target |
Returns
String | the path needed to change from source to target |
remove (path)
Remove a file at the given path
. Throws an error if path
is not a file
or a symbolic link to a file.
Parameters
String | path | the path of the file to remove. |
Throws
removeDirectory (path)
Remove a file or directory identified by path
. Throws an error if
path
is a directory and not empty.
Parameters
String | path | the directory path |
Throws
removeTree (path)
Remove the element pointed to by the given path. If path points to a directory, all members of the directory are removed recursively.
Example
// File system tree of the current working directory:
├── foo
│ └── bar
│ └── baz
├── musicfile.m4a
└── test.txt
fs.removeTree('foo');
After:
├── musicfile.m4a
└── test.txt
Parameters
null | path | the element to delete recursively |
resolve (paths...)
Join a list of paths by starting at an empty location and iteratively "walking" to each path given. Correctly takes into account both relative and absolute paths.
Example
>> fs.resolve('../.././foo/file.txt', 'bar/baz/', 'test.txt');
'../../foo/bar/baz/test.txt'
Parameters
null | paths... | the paths to resolve |
Returns
String | the joined path |
same (pathA, pathB)
Returns whether two paths refer to the same storage (file or directory), either by virtue of symbolic or hard links, such that modifying one would modify the other.
This function uses the POSIX stat()
function to compare two
files or links.
Parameters
String | pathA | the first path |
String | pathB | the second path |
Returns
Boolean | true if identical, otherwise false |
See
sameFilesystem (pathA, pathB)
Returns whether two paths refer to an entity of the same file system.
This function uses the POSIX stat()
function to compare two
paths by checking if the associated devices are identical.
Parameters
String | pathA | the first path |
String | pathB | the second path |
Returns
Boolean | true if same file system, otherwise false |
See
size (path)
Returns the size of a file in bytes, or throws an exception if the path does not correspond to an accessible path, or is not a regular file or a link.
Parameters
String | path | the file path |
Returns
Number | the file size in bytes |
Throws
split (path)
Split a given path into an array of path components.
Example
>> fs.split('/Users/someuser/Desktop/subdir/test.txt');
[ '', 'Users', 'someuser', 'Desktop', 'subdir', 'test.txt' ]
Parameters
String | path |
Returns
Array | the path components |
symbolicLink (source, target)
Creates a symbolic link at the target path that refers to the source path. The concrete implementation depends on the file system and the operating system.
This function wraps the POSIX symlink()
function, which may not work
on Microsoft Windows platforms.
Parameters
String | source | the source file |
String | target | the target link |
See
touch (path, mtime)
Sets the modification time of a file or directory at a given path to a specified time, or the current time. Creates an empty file at the given path if no file or directory exists, using the default permissions.
Parameters
String | path | the file path |
Date | mtime | optional date |
workingDirectory ()
Return the path name of the current working directory.
Returns
String | the current working directory |
write (path, content, options)
Open, write, flush, and close a file, writing the given content. If
content is a ByteArray
or ByteString
from the binary
module,
binary mode is implied.
Parameters
String | path | |
ByteArray|ByteString|String | content | |
Object | options |