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.
Example
// Writes a simple text file
const fs = require('fs');
if (!fs.exists('test.txt')) {
const textStream = fs.open('test.txt', {
write: true,
binary: false
});
try {
textStream.write('Hello World!');
textStream.flush();
} finally {
textStream.close();
}
console.log('Wrote test.txt');
} else {
console.error('test.txt already exists.');
}
Functions
- absolute (path)
- base (path, ext)
- canonical (path)
- changeGroup (path, group)
- changeOwner (path, owner)
- changePermissions (path, permissions)
- copy (from, to)
- copyTree (from, to)
- directory (path)
- exists (path)
- extension (path)
- getAttributes (path)
- group (path)
- hardLink (existing, link)
- 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 (existing, link)
- touch (path, mtime)
- workingDirectory ()
- write (path, content, options)
Path ()
Path constructor. Path is a chainable shorthand for working with paths.
Path.prototype. constructor
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
String | 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
String | target |
Path.prototype. toString ()
Path.prototype. valueOf ()
This is a non-standard extension, not part of CommonJS Filesystem/A.
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
String | 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.
Parameters
String | path | |
String | group | group name string |
changeOwner (path, owner)
Changes the owner of the specified file.
Parameters
String | path | |
String | owner | the user name string |
changePermissions (path, permissions)
Changes the permissions of the specified file.
Parameters
String | path | |
Number|String|java.util.Set<PosixFilePermission> | permissions | the POSIX permissions |
copy (from, to)
Read data from one file and write it into another using binary mode. Replaces an existing file if it exists.
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 |
getAttributes (path)
Returns basic attributes associated with a file in a file system.
Parameters
String | path |
Returns
Object | An Object with properties {creationTime, isDirectory, isOther, isRegularFile, isSymbolicLink, lastAccessTime, lastModifiedTime, size} |
group (path)
Returns the group name for the given file.
Parameters
String | path |
Returns
String | the group's name, or null if not possible to determine |
hardLink (existing, link)
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.
Parameters
String | existing | path to an existing file, therefore the target of the link |
String | link | the link to create pointing to an existing path |
Returns
String | the path to the link |
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
String | 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.
Parameters
String | path | the file path |
Returns
Boolean | true if the given file exists and is a symbolic link |
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
String | 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 Rhino-specific generator that produces the file names of a directory. There is no guarantee that the produced strings are in any specific order.
Example
// Iterates over the current working directory
for (let name of fs.iterate(".")) {
console.log(name);
}
Parameters
String | path | a directory path |
join ()
Join a list of path elements using the local file system's path separator.
Empty path elements (null, undefined and empty strings) will be skipped.
All non-string path elements will be converted to strings.
The result is not normalized, so join("..", "foo")
returns "../foo"
.
Example
// build path to the config.json file
const fullPath = fs.join(configDir, "config.json");
Returns
String | the joined path |
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 of strings naming the files and directories in the given directory. There is no guarantee that the strings are in any specific order.
Example
const names = fs.list('/usr/local/');
names.forEach(function(name) {
const fullPath = fs.join(dir, name);
if (fs.isFile(fullPath)) {
// do something with the file
}
});
Parameters
String | path | the directory path |
Returns
Array | an array of strings with the files, directories, or symbolic links |
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
String | 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
String | 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.
Parameters
String | path | the file path |
Number|String|java.util.Set<PosixFilePermission> | permissions | optional the POSIX permissions |
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
String | path | the path of the tree to create |
move (source, target)
Move a file from source
to target
. If target
already exists,
it is replaced by the source
file.
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
String | 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
or a text stream.
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
const m4aStream = fs.open('music.m4a', {
binary: true,
read: true
});
// The equivalent call with options as string
const m4aStream = fs.open('music.m4a', 'br');
// Opens a text file
const textStream = fs.open('example.txt', { read: true });
// The equivalent call with options as string
const 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
owner (path)
Returns the username of the owner of the given file.
Parameters
String | path |
Returns
String | the username of the owner, or null if not possible to determine |
path ()
A shorthand for creating a new Path
without the new
keyword.
permissions (path)
Returns the POSIX file permissions for the given path, if the filesystem supports POSIX.
Parameters
String | path |
Returns
PosixFilePermission the POSIX permissions for the given path |
read (path, options)
Read the content of the file corresponding to path
. Returns a
String or ByteString object depending on the options
argument. This function supports the same options as 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
.
Parameters
String | path | a file path |
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
String | 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
String... | 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.
Parameters
String | pathA | the first path |
String | pathB | the second path |
Returns
Boolean | true iff the two paths locate the same file |
sameFilesystem (pathA, pathB)
Returns whether two paths refer to an entity of the same file system.
Parameters
String | pathA | the first path |
String | pathB | the second path |
Returns
Boolean | true if same file system, otherwise false |
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 (existing, link)
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.
Parameters
String | existing | path to an existing file, therefore the target of the link |
String | link | the link to create pointing to an existing path |
Returns
String | the path to the symbolic link |
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 |