Path
Module | ejs |
Definition | final class Path |
Inheritance | Path ![]() |
Specified | ejscript-2.5 |
Stability | Evolving. |
Paths are filename objects and may or may not represent physical files in a file system.
That is, the corresponding file or directory for the Path may or may not exist. Once created, Paths are immutable and their path value cannot be changed.
Properties
Qualifiers | Property | Type | Description |
---|---|---|---|
get | absolute | Path | An equivalent absolute path equivalent for the current path. The path is normalized and uses the native system directory separator. On Windows, this path with contain a drive specifier and will have back-slash directory separators. On Cygwin, this path will be a Cygwin style path without a drive specifier and with forward-slash directory separators. If the path is outside the Cygwin filesystem (outside c:/cygwin), the path will have a /cygdrive/DRIVE prefix. To get a Windows style path, use the windows property accessor. |
get | accessed | Date | When the file represented by the path was last accessed. Set to null if the file does not exist. |
get | attributes | Object | File security permissions. |
get | basename | Path | The base of portion of the path. The base portion is the trailing portion without any directory elements. |
get | components | Array | Path components. The path is normalized and then broken into components for each directory level. The result is an array object with an element for each segment of the path. If the path is an absolute path, the first element represents the file system root and will be the empty string or drive spec on a Windows like systems. Array.join('/') can be used to put components back into a complete path. |
get | created | Date | When the file represented by the path was created. Set to null if the file does not exist. |
get | dirname | Path | The directory portion of a file. The directory portion is the leading portion including all directory elements and excluding the base name. On some systems, it will include a drive specifier. See also parent which will determine the parent directory of relative paths. |
get | exists | Boolean | Does a file exist for this path. |
get | extension | String | File extension portion of the path. The file extension is the portion after (and not including) the last '.'. Returns empty string if there is no extension 8. |
get | fileSystem | FileSystem | The file system containing this Path. |
get | hasDrive | Boolean | Does the file path have a drive spec (C:) in it's name. Only relevant on Windows like systems. |
get | isAbsolute | Boolean | Is the path absolute, i.e. Beginning at the file system's root. 8. |
get | isDir | Boolean | Is the path a directory. If the path is a symbolic link, the target of the link is tested. |
get | isLink | Boolean | Is the path is a symbolic link file. Not available on some platforms such as Windows and VxWorks. |
get | isRegular | Boolean | Is the path a regular file. If the path is a symbolic link, the target of the link is tested. |
get | isRelative | Boolean | Is the path is relative and not absolute. |
get | length | Number | The length of the path name in bytes. Note: this is not the file size. For that, use Path.size. |
get | linkTarget | Path | The target pointed to if this path is a symbolic link. Not available on some platforms such as Windows and VxWorks. If the path is not a symbolic link, it is set to null. 0. |
get | mimeType | String | Get the mime type for a path or extension string. The path's extension is used to lookup the corresponding mime type. |
get | modified | Date | When the file represented by the path was last modified. Set to null if the file does not exist. |
get | name | String | Name of the Path as a string. This is the same as toString(). |
get | natural | Path | Natural (native) respresentation of the path for the platform. This uses the platform file system path separator, this is '\' on Windows and '/' on unix and Cygwin. The returned path is normalized. See also portable for a portable representation. |
get | normalize | Path | Normalized representation of the path. This removes 'segment/..' and './' components. Separators are made uniform by converting all separators to be the same as the first separator found in the path. Note: the result is not converted to an absolute path. |
get | parent | Path | The parent directory of path. This may be an absolute path if there are no parent directories in the path. |
get set | perms | Number | The file permissions of a path. This number contains the Posix style permissions value or null if the file does not exist. NOTE: this is not a string representation of an octal posix mask. |
get | portable | Path | The path in a portable (like Unix) representation. This uses '/' separators. The value is is normalized and the separators are mapped to '/'. See also natural for convertion to the O/S native path representation. |
get | relative | Path | That path in a form relative to the application's current working directory. The value is normalized. |
get | root | Path | That root directory component of the path. On windows, this includes the drive spec if present in the path. |
get | separator | String | The path separator for this path. This will return the first path separator used by the path or the default file system path separator if the path has no separators. On Windows, a path may use '/' or '\' separators. Use natural portable or windows to create a new path with different path separators. |
get | size | Number | Size of the file associated with this Path object. Set to the number of bytes in the file or -1 if the size determination failed. |
get | windows | Path | An equivalent normalized Windows path equivalent for the current path. |
Path Class Methods
Qualifiers | Method |
---|
Path Instance Methods
Qualifiers | Method |
---|---|
Path(path: String = .) | |
Create a new Path object and set the path's location. | |
append(data, options = atw): Void | |
Append data to a file. | |
childOf(dir: Path): Boolean | |
Test if the path is a child of a given directory. | |
contains(pattern: String): Boolean | |
Test if the path name contains a substring. | |
copy(destination: Object, options: Object = null): Void | |
Copy a file to the destination. | |
endsWith(suffix: String): Boolean | |
Return true if the path ends with the given suffix. | |
files(patterns: Object = *, options: Object = null): Array | |
Get a list of matching files. | |
iterator override | get(): Iterator |
Get iterate over any files contained under this path (assuming it is a directory) 'for (v in files)'. | |
iterator override | getValues(): Iterator |
Get an iterator for this file to be used by 'for each (v in obj)'. | |
join(other: Array): Path | |
Join paths. | |
joinExt(ext: String, force: Boolean = false): Path | |
Join an extension to a path. | |
link(target: Path, hard: Boolean = false): Void | |
Create a target link to refer to the path This will remove any pre-existing target link and then create a symbolic link at the target to refer to the path. | |
makeDir(options: Object = null): Boolean | |
Make a new directory and all required intervening directories. | |
map(sep: String = separator): Path | |
Get a path after mapping the path directory separator. | |
match(pattern: RegExp): Array | |
Match the path to a regular expression pattern. | |
open(options: Object = null): File | |
Open a path and return a File object. | |
openBinaryStream(options: Object = null): BinaryStream | |
Open a file and return a BinaryStream object. | |
openTextStream(options: Object = null): TextStream | |
Open a file and return a TextStream object. | |
operate(from, to, control) | |
Operate on files. | |
readBytes(): ByteArray | |
Read the file contents as a ByteArray. | |
readJSON(): Object | |
Read the file containing a JSON string and return a deserialized object. | |
readLines(): Array | |
Read the file contents as an array of lines. | |
readString(): String | |
Read the file contents as a string. | |
readXML(): XML | |
Read the file contents as an XML object. | |
relativeTo(origin: Path = null): Path | |
Get a relative path to an origin. | |
remove(): Boolean | |
Delete the file associated with the Path object. | |
removeAll(): Boolean | |
Removes a directory and its contents If the path is a directory, this call will remove all subdirectories and their contents and finally the directory itself. | |
rename(target: Path): Void | |
Rename a file. | |
replace(pattern, replacement): Path | |
Search and replace. | |
replaceExt(ext: String): Path | |
Replace the path extension and return a new path. | |
resolve(otherPaths: Array): Path | |
Resolve paths in the neighborhood of this path. | |
same(other: Object): Boolean | |
Compare two paths test if they represent the same file. | |
setAttributes(attributes: Object): Void | |
Define file security permissions. | |
startsWith(prefix: String): Boolean | |
Return true if the path starts with the given prefix. | |
temp(): Path | |
Create a new temporary file. | |
override | toJSON(): String |
Convert the path to a JSON string. | |
toLowerCase(): Path | |
Convert the path to lower case. | |
override | toString(): String |
Return the path as a string. | |
trimComponents(count: Number): Path | |
Trim the requested number of path components from the start or end of the path. | |
trimEnd(pat: String): Path | |
Trim a pattern from the end of the path NOTE: this does a case-sensitive match. | |
trimExt(): Path | |
Trim a file extension from a path. | |
trimStart(pat: String): Path | |
Trim a pattern from the start of the path NOTE: this does a case-sensitive match. | |
truncate(size: Number): Void | |
Reduce the size of the file by truncating it. | |
write(args: Array): Void | |
Write the file contents. |
Method Detail
Path(path: String = .)
- Description
- Create a new Path object and set the path's location.
- Parameters
path: String Name of the path to associate with this path object. [default: .]
append(data, options = atw): Void
- Description
- Append data to a file.
- Parameters
data Data to append to the file. options File open options. Defaults to 'atw'. [default: atw]
- Description
- Test if the path is a child of a given directory.
- Parameters
dir: Path Path Parent directory to test.
- Returns
- True if the Path is a child of the specified parent directory.
- Description
- Test if the path name contains a substring. The pattern must be in portable format.
- Parameters
pattern: String String pattern to search for.
- Returns
- Boolean True if found.
- Description
- Copy a file to the destination.
- Parameters
destination: Object New file location. If the destination is a directory or ends with the file separator ('/'), the file is copied to that directory using the basename portion of the source filename. options: Object Object hash. [default: null]
- Options
permissions Set to a numeric Posix permissions mask. Not implemented. user String representing the file user name or numeric user id. If both user and uid are specified, user takes precedence. group String representing the file group name or numeric group id. If both group and gid are specified, group takes precedence.
- Description
- Return true if the path ends with the given suffix.
- Parameters
suffix: String String suffix to compare with the path.
- Returns
- True if the path does begin with the suffix.
- Description
- Get a list of matching files. This does Posix style glob file matching on supplied patterns and returns an
array of matching files.
This method supports several invocation forms:- files(pattern, {options})
- files([pattern, pattern, ...], {options})
- files({files: pattern, options...})
- files([{files: pattern, options...}])
A single pattern may be supplied with or with out options. Multiple patterns may be provided in an array. Alternatively, the pattern or patterns may be provided via an object with a 'files' property. In this case, the options are provided in the same object. If the pattern is omitted, the default is to search for all files under the Path by using '***'' as the pattern.
- Parameters
patterns: Object Pattern to match files. This can be a String, Path or array of String/Paths. If the Path is a directory, then files that match the specified patterns are returned. If the Path is not a directory, then the path itself is matched against the pattern. The following special sequences are supported: - The wildcard '?' matches any single character
- * matches zero or more characters in a filename or directory
- *** matches zero or more files or directories and matches recursively in a directory tree
- ! Negates pattern. This removes matching patterns from the set. These are applied after all source patterns have been processed. Use !! to escape or set noneg in options.
options: Object Optional properties to control the matching. [default: null]
- Options
contents Boolean If contents is set to true and the path pattern matches a directory, then return the contents of the directory in addition to the directory itself. This applies if the pattern matches an existing directory or the pattern ends with '/'. This is implemented by appending '***'' to the pattern. depthFirst Boolean Do a depth first traversal of directories. If true, then the directories will be shown after the files in the directory. Otherwise, directories will be listed first. Defaults to false. directories Boolean Include directories in the results. Defaults to true. exclude String | Regular | Function Blacklist of files to exclude from the results. Matches the full source path including the Path value. Only for the purpose of this match, directories will have '/' appended. If 'exclude' is a function, the file is not processed if the function returns true. The function callback has the form: Function(filename: Path, options: Object): Boolean The file argument is the filename being considered, it include the Path value. The value of "this" is set to the Path value. By default, exclude is set to exclude hidden files starting with '.' and files that look like temporary files. expand Object | Function Expand tokens in filenames using this object or function. If 'expand' is an object, then expand filename tokens of the form '{token}' using the object key values. If 'expand' is a function, it should have the signature: Function(filename: String, options: Object): String. hidden Boolean Include hidden files starting with '.' Defaults to false. include String | RegExp | Function Whitelist of files to include in the results. Matches the full source path including the Path value. Only for the purpose of this match, directories will have '/' appended. If 'include' is a function, the file is processed if the function returns true. The function callback has the form: Function(filename: Path, options: Object): Boolean The file argument is the filename being considered, it include the Path value. The value of "this" is set to the Path value. missing String Determine what happens if a pattern does not match any files. Set to undefined to report patterns that don't resolve by throwing an exception. Set to any non-null value to be used in the results in place of the pattern when there are no matching files or directories. Set to the empty string to use the pattern itself in the results. Set to null to do nothing and omit the pattern. Default is null. noneg Boolean Do not process negated file patterns. relative Boolean | String | Path Return filesnames relative to the path provided by the 'relative' option, otherwise results include the Path value. If set to true, the results will be relative to the current directory. Defaults to false.
- Returns
- An Array of Path objects for each file in the directory. The returned file list includes the Path itself. If the 'relative' option is provided, a path relative to that option is returned.
override iterator get(): Iterator
- Description
- Get iterate over any files contained under this path (assuming it is a directory) 'for (v in files)'. This operates the same as getValues on a Path object.
- Returns
- An iterator object.
- Example
for (f in Path('.')) @
override iterator getValues(): Iterator
- Description
- Get an iterator for this file to be used by 'for each (v in obj)'. Return This operates the same as get on a Path object.
- Returns
- An iterator object.
- Example
for each (f in Path('.'))
- Description
- Join paths. Joins one more more paths together. If the other path is absolute, return it. Otherwise add a separator, and continue joining. The separator is chosen to match the first separator found in either path. If none found, the default file system path separator is used.
- Returns
- A new joined, normalized Path object. 0.
- Description
- Join an extension to a path. If the base name of the path already has an extension, this call does nothing.
- Parameters
ext: String Extension to add. The extension may or may not contain a leading period. Best practice is to not have leading periods on extensions. force: Boolean Set to true to always add the extension. [default: false]
- Returns
- A new Path object with the given extension if the path did not already have one. P.
- Description
- Create a target link to refer to the path This will remove any pre-existing target link and then create a symbolic link at the target to refer to the path.
- Description
- Make a new directory and all required intervening directories. If the directory already exists, the function returns without any further action.
- Options
permissions Directory permissions to use for all created directories. Set to a numeric Posix permissions mask. user String representing the file user. If both user and uid are specified, user takes precedence. group String representing the file group. If both group and gid are specified, group takes precedence. uid Number representing the file user id. gid Number representing the file group id.
- Returns
- True if the directory can be made or already exists.
- Description
- Get a path after mapping the path directory separator.
- Parameters
sep: String Path directory separator to use. Defaults to the separator for this path. [default: separator]
- Returns
- A new Path after mapping separators.
- Description
- Match the path to a regular expression pattern.
- Parameters
pattern: RegExp The regular expression pattern to search for.
- Returns
- Returns an array of matching substrings in the path.
- Description
- Open a path and return a File object.
- Options
mode Optional file access mode string. Use 'r' for read, 'w' for write, 'a' for append to existing content, '+' never truncate. permissions Optional Posix permissions number mask. Defaults to 0664. user String representing the file user. group String representing the file group.
- Returns
- A File object which implements the Stream interface.
- Throws
- IOError: if the path or file cannot be created.
openBinaryStream(options: Object = null): BinaryStream
- Description
- Open a file and return a BinaryStream object.
- Parameters
options: Object Optional options object. [default: null]
- Options
mode Optional file access mode with values ored from: Read, Write, Append, Create, Open, Truncate. Defaults to Read. permissions Optional Posix permissions number mask. Defaults to 0664. user String representing the file user. group String representing the file group.
- Returns
- A BinaryStream object which implements the Stream interface.
- Throws
- IOError: if the path or file cannot be opened or created.
openTextStream(options: Object = null): TextStream
- Description
- Open a file and return a TextStream object.
- Parameters
options: Object Optional options object. [default: null]
- Options
mode Optional file access mode string. Use 'r' for read, 'w' for write, 'a' for append to existing content, '+' never truncate. encoding Text encoding format. permissions Optional Posix permissions number mask. Defaults to 0664. user String representing the file user. group String representing the file group.
- Returns
- A TextStream object which implements the Stream interface.
- Throws
- IOError: if the path or file cannot be opened or created. H
operate(from, to, control)
- Description
- Operate on files. This may be used to copy, move or process files.
This method supports several invocation forms:- operate(from, to)
- operate(from, to, {options})
- operate([from, from, ...], to, {options})
- operate({from: pattern, to: directory, options...})
- operate([{from: pattern, to: directory, options...}])
The 'from' patterns are resolved using the #Path.files method to create an input files list. All the options for Path.files are supported.
Operate will resolve the input patterns relative to the Path itself. If copying, that directory portion relative to the Path will be appended to the destination 'to' argument. In this manner, entire directory trees can be easily copied.
- Parameters
from Path | String | Object | Array This may be a String or Path containing the source paths to process. Alternatively, it may be an object that supplies 'from', 'to' and 'options' as processing instructions. It may also be an array of Paths, Strings or Objects. The 'from' patterns may contain: ? ! Negates pattern. This removes matching patterns from the set. These are applied after all source patterns have been processed. Use !! to escape. If item is a directory or ends with '/', then "***"" is automatically appended to match the directory contents. to String | Path Destination target. If 'from' is a Path or String, then the 'to' argument must be a destination Path or String. If 'from' is an Object or Array of instruction objects that contains a 'to' property, then 'to' should be omitted and will be ignored. If multiple source files are specified or the destination ends in the separator '/', the destination is assumed to be a directory. If the destination is a directory, the destination filename is created by appending the the source path to the directory. control Additional processing instructions. All the options provided by #Path.files are also supported.
- Options
active Boolean If destination is an active executable or library, rename the active file using a '.old' extension and retry. compress Boolean Compress destination file using Zlib. Results in a '.gz' extension. divider String Divider text to use between appended files. extension String | Path Extension to use for the destination filenames. extensionDot String Specifies where the filename extension begins for filenames with multiple dots. Set to 'first' or 'last'. filter RegExp Pattern of lines to filter out from appended files. flatten Boolean Flatten the input source tree to a single level. Defaults to true. footer String Footer to append when appending files. group String | Number System group name or number to use for the destination files. header String Header prepend when appending files. isDir Assume the destination is a directory. Create if it does not exist. Same as appending a trailing '/' to the 'to' argument. keep Boolean Keep uncompressed file after compressing. operation String Set to 'append' to append files, 'copy' to copy files and 'move' to move files. Set to 'list' to return a file list in options.list and perform no operations. Defaults to 'copy' if unset. patch Object. Expand file contents tokens using this object. Object hash containing properties to use when replacing tokens of the form {token} in file contents. perform Function Callback function to perform the operation on a matching file. This function should return true if it handles the file and default processing is not required. Note that post processing still occurs including compression and stripping if required regardless of the return value. Function(from: Path, to: Path, options: Object): Boolean. permissions Number Posix style permissions mask. E.g. 0644. postPerform Function. Callback function to invoke after performing the operation. Function(from, to, options): Path. prePerform Function. Callback function to invoke before performing the operation. Function(from, to, options): Path. relative Boolean | String | Path Create destination filenames relative to the path provided by the 'relative' option, otherwise destination filenames include the Path value. If set to true, the destination will be relative to the current directory. If set, implies flatten == false. Defaults to false. rename Function Callback function to provide a new destination filename. Function(from, to, options): Path. strip Boolean Run 'strip' on the destination files. symlink String | Path Create a symbolic link to the destination. If symlink has a trailing '/' a link is created in the directory specified by 'symlink' using the source file basename as the link name. trim Number of path components to trim from the start of the source filename. If set, implies flatten == false. user String | Number System user account name or number to use for destination files. verbose True | function. If true, then trace to stdout. Otherwise call function for each item.
- Returns
- The number of files processed. If the operation is 'list', returns the expanded source file list.
readBytes(): ByteArray
- Description
- Read the file contents as a ByteArray. This method opens the file, reads the contents, closes the file and returns a new ByteArray with the contents.
- Returns
- A ByteArray.
- Throws
- IOError: if the file cannot be read
- Example
var b: ByteArray = Path('/tmp/a.txt').readBytes()
readJSON(): Object
- Description
- Read the file containing a JSON string and return a deserialized object. This method opens the file, reads the contents, deserializes the object and closes the file.
- Returns
- An object.
- Throws
- IOError: if the file cannot be read
- Example
data = Path('/tmp/a.json').readJSON()
readLines(): Array
- Description
- Read the file contents as an array of lines. Each line is a string. This method opens the file, reads the contents and closes the file.
- Returns
- An array of strings.
- Throws
- IOError: if the file cannot be read
- Example
for each (line in Path('/tmp/a.txt').readLines())
readString(): String
- Description
- Read the file contents as a string. This method opens the file, reads the contents and closes the file.
- Returns
- A string.
- Throws
- IOError: if the file cannot be read
- Example
data = Path('/tmp/a.txt').readString()
readXML(): XML
- Description
- Read the file contents as an XML object. This method opens the file, reads the contents and closes the file.
- Returns
- An XML object.
- Throws
- IOError: if the file cannot be read
- Description
- Get a relative path to an origin.
- Parameters
origin: Path The origin path to use when calculating a relative path to the destination (this path). If origin is null, the current working directory is used as the origin. [default: null]
- Returns
- A new relative path.
remove(): Boolean
- Description
- Delete the file associated with the Path object. If this is a directory without contents it will be removed.
- Returns
- True if the file is sucessfully deleted or does not exist.
removeAll(): Boolean
- Description
- Removes a directory and its contents If the path is a directory, this call will remove all subdirectories and their contents and finally the directory itself. If the directory does not exist, this call does not error and does nothing.
- Returns
- True if all the contents are sucessfully deleted or if the directory does not exist. Otherwise return false.
replace(pattern, replacement): Path
- Description
- Search and replace. Search for the given pattern which can be either a string or a regular expression and replace it with the replace text. If the pattern is a string, only the first occurrence is replaced.
- Parameters
pattern The regular expression or string pattern to search for. replacement The string to replace the match with or a function to generate the replacement text. The replacement string can contain special replacement patterns: '$' inserts a '$', '$&' inserts the matched substring, '$`' inserts the portion that preceeds the matched substring, '$'' inserts the portion that follows the matched substring, and '$N' inserts the Nth parenthesized substring. The replacement parameter can also be a function which will be invoked and the function return value will be used as the resplacement text. The function will be invoked multiple times for each match to be replaced if the regular expression is global. The function will be invoked with the signature: function (matched, submatch_1, submatch_2, ..., matched_offset, original_string).
- Returns
- Returns a new string.
- Specified
- ejscript-2.5
- Description
- Replace the path extension and return a new path.
- Returns
- A new path with the given extension.
- Description
- Resolve paths in the neighborhood of this path. Resolve operates like join, except that it joins the
given paths to the directory portion of the current ('this') path. For example:
Path('/usr/bin/ejscript/bin').resolve('lib') will return '/usr/lib/ejscript/lib'. i.e. it will return the
sibling directory 'lib'.
Resolve operates by determining a virtual current directory for this Path object. It then successively joins the given paths to the directory portion of the current result. If the next path is an absolute path, it is used unmodified. The effect is to find the given paths with a virtual current directory set to the directory containing the prior path.
Resolve is useful for creating paths in the region of the current path and gracefully handles both absolute and relative path segments.
- Parameters
otherPaths: Array Paths to resolve in the region of this path.
- Returns
- A new Path object that is resolved against the prior path.
- Description
- Compare two paths test if they represent the same file.
- Parameters
other: Object Other path to compare with.
- Returns
- True if the paths represent the same underlying filename 8.
- Description
- Define file security permissions.
- Options
user String representing the file user name If both user and uid are specified, user takes precedence. group String representing the file group name If both group and gid are specified, group takes precedence. uid Number representing the file user id. gid Number representing the file group id. permissions Number File Posix permissions mask.
- Description
- Return true if the path starts with the given prefix.
- Parameters
prefix: String String prefix to compare with the path.
- Returns
- True if the path does begin with the prefix.
temp(): Path
- Description
- Create a new temporary file. The temp file is located in the directory specified by the Path object. If the path object is created with an empty path value, the temporary file will be created in the standard system location for temp files. This is typically /tmp or /temp.
- Returns
- A new Path object for the temp file.
override toJSON(): String
- Description
- Convert the path to a JSON string.
- Returns
- A JSON string representing the path.
toLowerCase(): Path
- Description
- Convert the path to lower case.
- Returns
- A new Path mapped to lower case.
override toString(): String
- Description
- Return the path as a string. The path is not translated.
- Returns
- A string representing the path.
- Description
- Trim the requested number of path components from the start or end of the path.
- Parameters
count: Number Number of directory components to remove. If negative, trim from the end.
- Returns
- Trimmed path.
- Description
- Trim a pattern from the end of the path NOTE: this does a case-sensitive match.
- Returns
- A Path containing the trimmed path name.
trimExt(): Path
- Description
- Trim a file extension from a path.
- Returns
- A Path with no extension.
- Description
- Trim a pattern from the start of the path NOTE: this does a case-sensitive match.
- Returns
- A Path containing the trimmed path name.
- Description
- Write the file contents. This method opens the file, writes the contents and closes the file.
- Parameters
args: Array The data to write to the file. Data is serialized in before writing. Note that numbers will not be written in a cross platform manner. If that is required, use the BinaryStream class to write Numbers.
- Throws
- IOError: if the data cannot be written