Readonly
rawAlias for .dirname()
.
Return the path to the parent directory.
$ path('/usr/local/bin').parent.raw
'/usr/local' // on POSIX
$ path('C:\\Users\\fuu').parent.raw
'C:\\Users' // on Windows
Get (when 0 args) or set (when 1 arg) the directory name of the path.
If the argument is a function, it should accept a string of the old dirname and return a string as the new dirname.
$ path('/usr/local/bin').dirname().raw
'/usr/local' // on POSIX
$ path('C:\\Users\\fuu').dirname().raw
'C:\\Users' // on Windows
$ path('./src/index.ts').dirname('./dist').raw
'dist/index.ts' // on POSIX
'dist\\index.ts' // on Windows
$ path('path-nice/dist/types.ts').dirname(old => old.replace(/dist/g, 'build')).raw
'path-nice/build/types.ts' // on POSIX
'path-nice\\build\\types.ts' // on Windows
Optional
newDirname: string | PathNice<unknown> | ((oldDirname: string) => string)Get (when 0 args), set (when arg is a string or a function) or remove (when arg is null) the extension of the path, from the last '.' to end of string in the last portion of the path.
When getting the filename, if there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string.
When setting the filename, it will only modifiy the path string and will not actually rename the file.
$ path('./src/index.js').ext()
'.js'
$ path('./LICENSE').ext()
''
$ path('.bashrc').ext()
''
$ path('./src/index.js').ext('.ts').raw
'./src/index.ts' // on POSIX
'./src\\index.ts' // on Windows
$ path('./public/help.htm').ext(
ext => ext === '.htm' ? '.html' : ext
).raw
'./public/help.html' // on POSIX
'./public\\help.html'// on Windows
$ path('./README.md').ext(null).raw
'./README' // on POSIX
'.\\README' // on Windows
Get (when 0 args) or set (when 1 arg) the filename of the path.
When getting the filename, technically, it will firstly convert the path to an absolute path, then return its last portion. Therefore, for relative paths ". /", this method can also get the file name. If the path is root directory, it returns ''.
When setting the filename, it will only modifiy the path string and will not actually rename the file. If the argument is a function, it should accept a string of the old filename and return a string as the new filename.
$ path('./src/index.js').filename()
'index.js'
$ path('/home/fuu///').filename()
'fuu' // on POSIX
$ path('/home/fuu/bar.txt').filename('foo.md').raw
'/home/fuu/foo.md' // on POSIX
$ path('C:\\Users\\fuu\\\\\\').filename()
'fuu' // on Windows
$ path('C:\\Users\\fuu\\bar.txt').filename('foo.md').raw
'C:\\Users\\fuu\\foo.md' // on Windows
$ path('./data/storage.json').filename(n => 'old.' + n).raw
'data/old.storage.json' // on POSIX
'data\\old.storage.json' // on Windows
Determine whether path is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.
// on POSIX
path('/foo/bar').isAbsolute(); // true
path('/baz/..').isAbsolute(); // true
path('qux/').isAbsolute(); // false
path('.').isAbsolute(); // false
// on Windows
path('//server').isAbsolute(); // true
path('\\\\server').isAbsolute(); // true
path('C:/foo/..').isAbsolute(); // true
path('C:\\foo\\..').isAbsolute(); // true
path('bar\\baz').isAbsolute(); // false
path('bar/baz').isAbsolute(); // false
path('.').isAbsolute(); // false
Join this path with all arguments together and normalize the resulting path.
$ path('../data').join('settings.json').raw
'../data/settings.json' // on POSIX
'..\\data\\settings.json' // on Windows
$ path('/home').join('fuu', 'data.json').raw
'/home/fuu/data.json' // on POSIX
$ path('C:\\Users').join('fuu', 'data.json').raw
'C:\\Users\\fuu\\data.json' // on Windows
Rest
...paths: (string | PathNice<unknown>)[]Return an object whose properties represent significant elements of the path.
// on POSIX
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┐ ├──────┬─────┤
│ root │ │ name │ ext │
" / home/user/dir / file .txt "
└──────┴──────────────┴──────┴─────┘
$ const result = path('/home/fuu/data.json').parse()
$ result.root()
'/'
$ result.dir()
'/home/fuu'
$ result.base()
'data.json'
$ result.ext()
'.json'
$ result.name()
'data'
$ result.dir('/root').ext('.txt').format().raw
'/root/data.txt'
// on Windows
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┐ ├──────┬─────┤
│ root │ │ name │ ext │
" C:\ path\dir \ file .txt "
└──────┴──────────────┴──────┴─────┘
$ const result = path('C:\\Users\\fuu\\data.json').parse()
$ result.root()
'C:\\'
$ result.dir()
'C:\\Users\\fuu'
$ result.base()
'data.json'
$ result.ext()
'.json'
$ result.name()
'data'
$ result.dir('D:\\path-nice').ext('.txt').format().raw
'D:\\path-nice\\data.txt'
Add a postfix to the end of the path.
This will only modifiy the path string and will not actually rename the file.
$ path('user/data/').postfix('-1').raw
'user/data-1' // on POSIX
'user\\data-1' // on Windows
$ path('./content.txt').postfix('.json').raw
'./content.txt.json' // on POSIX
'.\\content.txt.json' // on Windows
Add a postfix to the filename, but before the extension. If the extension not exists, directly add to the end.
This will only modifiy the path string and will not actually rename the file.
$ path('path-nice/tsconfig.json').postfixBeforeExt('.base').raw
'path-nice/tsconfig.base.json' // on POSIX
'path-nice\\tsconfig.base.json' // on Windows
Add a prefix to the filename, i.e. add the prefix after dirname, before filename.
This will only modifiy the path string and will not actually rename the file.
$ path('data/January').prefixFilename('2021-').raw
'data/2021-January' // on POSIX
'data\\2021-January' // on Windows
Asynchronously computes the canonical pathname by resolving .
, ..
, and symbolic
links.
Get (when 0 args) or set (when 1 arg) the path segment separator.
When get, return 'none' if there is no separator in the path, or 'hybrid' if there are both '/' and '\' separators.
$ path('/home/fuu/data.json').separator()
'/'
$ path('C:\\Windows\\System32').separator()
'\\'
$ path('index.js').separator()
'none'
$ path('C:\\Windows/System32').separator()
'hybrid'
$ path('/home/fuu/data.json').separator('\\').raw
'\\home\\fuu\\data.json'
$ path('C:\\Windows\\System32').separator('/').raw
'C:/Windows/System32'
Resolve the path to an absolute path, if it isn't now.
$ path('./src/index.ts').toAbsolute().raw // on POSIX,
// suppose cwd is '/path-nice'
'/path-nice/src/index.ts'
$ path('./src/index.ts').toAbsolute().raw // on Windows,
// suppose cwd is 'D:\\path-nice'
'D:\\path-nice\\src\\index.ts'
$ path('./src/index.ts').toAbsolute('/work').raw // on POSIX
'/work/src/index.ts'
$ path('./src/index.ts').toAbsolute('D:\\work').raw // on Windows
'D:\\work\\src\\index.ts'
Optional
basePath: string | PathNice<unknown>(optional) to where the current path is relative. Must be an absolute path. If not set, current working directory is used.
Solve the relative path by comparing with {relativeTo}. At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve.
The default value of relativeTo
is current working directory.
$ path('./src/index.ts').toAbsolute().toRelative('./')
'src/index.ts' // on POSIX
'src\\index.ts' // on Windows
$ path('/data/orandea/impl/bbb').toRelative('/data/orandea/test/aaa').raw
'../../impl/bbb' // on POSIX
$ path('C:\\orandea\\impl\\bbb').toRelative('C:\\orandea\\test\\aaa').raw
'..\\..\\impl\\bbb' // on Windows
Optional
relativeTo: string | PathNice<unknown>Asynchronously append data to a file, creating the file if it does not yet exist.
can be a string or a Buffer
Optional
options: null | BufferEncoding | { encoding?: null | string; flag?: string | number; mode?: string | number }If options is a string, then it specifies the encoding.
options.encoding
Default: 'utf8'options.mode
only affects the newly created file. See fs.open() for more
details. Default: 0o666options.flag
See support of file system flags. Default: 'a'.Roughly same as fs.createReadStream()
, but no need to specify the path.
See fs.createReadStream(path[, options]) for full document.
Optional
options: string | { autoClose?: boolean; emitClose?: boolean; encoding?: string; end?: number; fd?: number | FileHandle; flags?: string | number; fs?: any; highWaterMark?: number; mode?: string | number; start?: number }Roughly same as fs.createWriteStream()
, but no need to specify the path.
See fs.createWriteStream(path[, options]) for full document.
Optional
options: string | { autoClose?: boolean; emitClose?: boolean; encoding?: string; fd?: number | FileHandle; flags?: string | number; fs?: any; mode?: string | number; start?: number }Roughly same as fs.promise.open()
, but no need to specify the path.
Opens a FileHandle.
Refer to the POSIX open(2) documentation for more detail.
Some characters (< > : " / \ | ? *
) are reserved under Windows as documented by
Naming Files, Paths, and Namespaces.
Under NTFS, if the filename contains a colon, Node.js will open a file system
stream, as described by this MSDN page.
Optional
flags: string | numberOptional
mode: string | numberSimilar to .writeFile(), except that if the parent directory does not exist, it will be created automatically.
Optional
options: null | string | { encoding?: null | string; flag?: string | number; mode?: string | number; signal?: AbortSignal }Similar to .writeJSON(), except that if the parent directory does not exist, it will be created automatically.
Optional
options: null | string | { EOL?: "\n" | "\r\n"; encoding?: null | string; flag?: string | number; mode?: string | number; replacer?: null | (string | number)[] | ((this: any, key: string, value: any) => any); spaces?: string | number }Roughly same as fs.promises.readFile()
, but no need to specify the path.
Asynchronously reads the entire contents of a file.
If no encoding is specified (using options.encoding), the data is returned as a
If options is a string, then it specifies the encoding.
options.encoding
Default: nulloptions.flag
See support of file system flags. Default: 'r'options.signal
allows aborting an in-progress readFileIt is possible to abort an ongoing readFile
using an AbortSignal
. If a
request is aborted the promise returned is rejected with an AbortError
:
import path from 'path-nice';
try {
const controller = new AbortController();
const { signal } = controller;
const promise = path(filename).readFile({ signal });
// Abort the request before the promise settles.
controller.abort();
await promise;
} catch (err) {
// When a request is aborted - err is an AbortError
console.error(err);
}
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering fs.readFile
performs.
Optional
options: null | { encoding?: null; flag?: string | number; signal?: AbortSignal }Optional
options: null | string | { encoding?: null | string; flag?: string | number; signal?: AbortSignal }Similar to .readFile()
, but guaranteed to return a string, use UTF-8 by default.
Asynchronously reads the entire contents of a file.
Optional
options: null | BufferEncoding | { encoding?: null | BufferEncoding; flag?: string | number; signal?: AbortSignal }if options is a string, then it specifies the encoding.
options.encoding
Default: 'utf8'options.flag
See support of file system flags. Default: 'r'options.signal
allows aborting an in-progress readFileIt is possible to abort an ongoing readFile
using an AbortSignal
. If a
request is aborted the promise returned is rejected with an AbortError
:
import path from 'path-nice';
try {
const controller = new AbortController();
const { signal } = controller;
const promise = path(filename).readFileToString({ signal });
// Abort the request before the promise settles.
controller.abort();
await promise;
} catch (err) {
// When a request is aborted - err is an AbortError
console.error(err);
}
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering fs.readFile
performs.
Asynchronously reads a JSON file and then parses it into an object.
If options is a string, then it specifies the encoding.
options.encoding
Default: 'utf8'options.flag
See support of file system flags. Default: 'r'Optional
options: null | BufferEncoding | { encoding?: null | BufferEncoding; flag?: string | number }Execute the given function with the original content of the file as input, and the returned string will become the new content of the file.
can also return a Promise<string>
Optional
options: null | BufferEncoding | { encoding?: null | BufferEncoding }If options is a string, then it specifies the encoding.
options.encoding
Default: 'utf8'Asynchronously update the json object of the file.
accepts a object paresd from the JSON file, can return a new object or undefined (in that case, original object is used) to overwrite the file. It can also return a Promise that resolves to an object or undefined.
Optional
options: null | BufferEncoding | { encoding?: null | BufferEncoding }If options is a string, then it specifies the encoding.
options.encoding
Default: 'utf8'Roughly same as fs.promises.writeFile()
, but no need to specify the path.
Asynchronously writes data to a file, replacing the file if it already exists.
It is unsafe to call fsPromises.writeFile()
multiple times on the same file
without waiting for the Promise
to be resolved (or rejected).
can be a string, a
Optional
options: null | string | { encoding?: null | string; flag?: string | number; mode?: string | number; signal?: AbortSignal }If options is a string, then it specifies the encoding.
options.encoding
Default: 'utf8'options.mode
Default: 0o666options.flag
See support of file system flags. Default: 'w'.options.signal
allows aborting an in-progress writeFileIt is possible to use an
import { writeFile } from 'fs/promises';
import { Buffer } from 'buffer';
try {
const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
const promise = writeFile('message.txt', data, { signal });
// Abort the request before the promise settles.
controller.abort();
await promise;
} catch (err) {
// When a request is aborted - err is an AbortError
console.error(err);
}
Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering writeFile() performs.
Asynchronously writes an object to a JSON file.
Optional
options: null | string | { EOL?: "\n" | "\r\n"; encoding?: null | string; flag?: string | number; mode?: string | number; replacer?: null | (string | number)[] | ((this: any, key: string, value: any) => any); spaces?: string | number }a string to specify the encoding, or an object:
options.EOL
: set end-of-line character. Default: '\n'.options.replacer
: passed to JSON.stringify(). A function that alters the behavior
of the stringification process, or an array of strings or numbers naming properties
of value that should be included in the output. If replacer is null or not provided,
all properties of the object are included in the resulting JSON string.options.spaces
: passed to JSON.stringify(). A string or number used to insert
white space (including indentation, line break characters, etc.) into the output
JSON string for readability purposes.options.encoding
Default: 'utf8'options.mode
Default: 0o666options.flag
See support of file system flags. Default: 'w'.Similar to fs.promises.cp(), except that the default value of options.recursive
is true.
Asynchronously copies a file or directory to dest, including subdirectories and files when copying a directory.
destination path wrapped in Promise
destination path to copy to.
Optional
options: { dereference?: null | boolean; errorOnExist?: null | boolean; filter?: null | ((src: string, dest: string) => boolean | Promise<boolean>); force?: null | boolean; preserveTimestamps?: null | boolean; recursive?: null | boolean; verbatimSymlinks?: null | boolean }options.force
: overwrite existing file or directory. The copy operation will
ignore errors if you set this to false and the destination exists. Use the
errorOnExist
option to change this behavior. Default: true.
options.dereference
: dereference symlinks. Default: false.options.errorOnExist
: when force is false, and the destination exists, throw an
error. Default: false.options.filter
: Function to filter copied files/directories. Return true to copy
the item, false to ignore it. Can also return a Promise that resolves to true or
false. Default: undefined.options.preserveTimestamps
: When true timestamps from src will be preserved.
Default: false.options.recursive
: copy directories recursively. Default: trueoptions.verbatimSymlinks
: When true, path resolution for symlinks will be
skipped. Default: falseOptional
dereference?: null | booleanOptional
errorOptional
filter?: null | ((src: string, dest: string) => boolean | Promise<boolean>)Optional
force?: null | booleanOptional
preserveOptional
recursive?: null | booleanOptional
verbatimAsynchronously removes a file or directory. The directory can have contents. If the path does not exist, silently does nothing.
original path wrapped in Promise
Asynchronously ensures that a directory is empty. Deletes directory contents if the directory is not empty. If the directory does not exist, it is created. The directory itself is not deleted.
original path wrapped in Promise
Asynchronously moves a file or directory to dest, even across devices, including subdirectories and files when moving a directory.
destination path wrapped in Promise
destination to move to. Note: When src is a file, dest must be a file and when src is a directory, dest must be a directory.
Optional
options: { overwrite?: null | boolean }options.overwrite: overwrite existing file or directory. Default: false
Optional
overwrite?: null | booleanAsynchronously removes a file or directory. The directory can have contents. If the path does not exist, silently does nothing.
original path wrapped in Promise
Asynchronously ensures that a directory is empty. Deletes directory contents if the directory is not empty. If the directory does not exist, it is created. The directory itself is not deleted.
original path wrapped in Promise
Asynchronously ensures that the directory exists. If the directory structure does not exist, it is created.
original path wrapped in Promise
Optional
options: { mode?: string | number }options.mode: mode of the newly created directory. Default: 0o777
Optional
mode?: string | numberAsynchronously ensures that the file exists. If the file that is requested to be created is in directories that do not exist, these directories are created. If the file already exists, it is NOT MODIFIED.
original path wrapped in Promise
Optional
options: { dirMode?: string | number; fileMode?: string | number }options.fileMode: mode of the newly created file. Default: 0o777
0o777
Optional
dirOptional
fileNote: It is recommended to use isFile()
, isDir()
, etc to indicate the type of
file you want to check.
Asynchronously check whether the path exists.
Asynchronously check whether the path exists and is a directory.
Optional
followlink: booleanwhen true, if the path is a link, follows it. Default: false
Asynchronously check whether the path exists and is an empty directory.
Note: if the path is inaccessible or not a directory, it also returns false.
Optional
followlink: booleanwhen true, if the path is a link, follows it. Default: false
Asynchronously check whether the path exists and is a file.
Optional
followlink: booleanwhen true, if the path is a link, follows it. Default: false
Asynchronously check whether the path exists and is a symbolic link.
Asynchronously list all directories and files under the folder, return a Promise
that resolves to an object { dirs: PathNiceArr; files: PathNiceArr }
.
dirs
: subdirectories, not including the current folderfiles
: files and others (e.g. device, FIFO, socket, etc). If followLinks
is
false, it also contains links.The paths wrapped in the returned PathNice
object are all absolute paths, so
they can be used directly for .readFile()
, .writeFile()
, .copy()
, .move()
,
etc. Use .toRelative(dir)
to get the relative path.
const { dirs, files } = await path('./').ls();
await Promise.all(
files
.filter(f => f.ext() === '.json')
.map(async f => {
await f.updateJSON(json => { json.timestamp = Date.now() });
await f.copy(f.dirname('../backup'));
})
);
await dirs.remove();
Optional
recursive: booleanwhether to list file recursively. Default: false
Optional
followLinks: booleanwhether to follow links under the folder. Default: false
Roughly same as fs.promises.readdir()
, but no need to specify the path.
Reads the contents of a directory.
The optional options argument can be a string specifying an encoding, or an object
with an encoding property specifying the character encoding to use for the
filenames. If the encoding is set to 'buffer', the filenames returned will be
passed as
If options.withFileTypes is set to true, the resolved array will contain <fs.Dirent> objects.
try {
const files = await path('path/to/dir').readdir();
for (const file of files)
console.log(file);
} catch (err) {
console.error(err);
}
Optional
options: null | BufferEncoding | { encoding?: null | BufferEncoding; withFileTypes?: false }a string to specify the encoding, or an object:
options.encoding
Default: 'utf8'options.withFileTypes
Default: falseOptional
options: string | { encoding: string; withFileTypes?: false }Optional
encoding?: null | BufferEncodingRoughly same as fs.watchFile()
, but no need to specify the path.
Stop watching for changes on filename. If listener is specified, only that particular listener is removed. Otherwise, all listeners are removed, effectively stopping watching of filename.
Calling .unwatchFile() with a filename that is not being watched is a no-op, not an error.
Optional
listener: ((curr: Stats, prev: Stats) => void)Watch for changes on the path, which can be either a file or a directory.
The second argument is optional. If options
is provided as a string, it
specifies the encoding
. Otherwise options
should be passed as an object.
The listener callback gets two arguments (eventType, filename)
. eventType
is
either 'rename'
or 'change'
, and filename
is the name of the file
which triggered the event.
On most platforms, 'rename'
is emitted whenever a filename appears or
disappears in the directory.
The listener callback is attached to the 'change'
event fired by fs.FSWatcher
,
but it is not the same thing as the 'change'
value ofeventType
.
If a signal
is passed, aborting the corresponding AbortController will close
the returned fs.FSWatcher
.
Optional
listener: WatchListener<Buffer>Optional
options: null | BufferEncoding | WatchOptionsOptional
listener: WatchListener<string>Optional
listener: WatchListener<string | Buffer>Optional
listener: WatchListener<string>Note: Using .watch()
or .watchWithChokidar()
is more efficient than this method.
Roughly same as fs.watchFile()
, but no need to specify the path.
Refer to https://nodejs.org/api/fs.html#fswatchfilefilename-options-listener
Watch file changes with chokidar for a more friendly and powerful API.
This method is equivalent to calling chokidar.watch(path, options)
, where path
is populated with the current path and the options
accepted by this method are
passed to it.
See https://github.com/paulmillr/chokidar#api for full documents.
⚠️ Note: chokidar can only use the original node:fs
module. Calling this method
will result in an error if you are using a path-nice generated via bindFS()
that
is bound to another fs implementation. If you are sure your operation makes sense,
enable options.forceEvenDifferentFS
to ignore this error.
Optional
options: WatchOptions & { forceEvenDifferentFS?: boolean }Asynchronous chmod(2) - Change permissions of a file.
A file mode. If a string is passed, it is parsed as an octal integer.
Asynchronous chown(2) - Change ownership of a file.
Asynchronously gets the file mode.
Asynchronously gets the uid and gid of the file owner.
Asynchronously gets the file size.
Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links.
Asynchronous lstat(2) - Get file status. Does not dereference symbolic links.
Optional
options: StatOptions & { bigint?: false }Optional
options: StatOptionsAsynchronous stat(2) - Get file status.
Optional
opts: StatOptions & { bigint?: false }Optional
opts: StatOptionsSynchronously append data to a file, creating the file if it does not yet exist.
can be a string or a Buffer
Optional
options: null | BufferEncoding | { encoding?: null | string; flag?: string | number; mode?: string | number }If options is a string, then it specifies the encoding.
options.encoding
Default: 'utf8'options.mode
only affects the newly created file. See fs.open() for more
details. Default: 0o666options.flag
See support of file system flags. Default: 'a'.Roughly same as fs.openSync()
, but no need to specify the path.
Returns an integer representing the file descriptor.
For detailed information, see the documentation fs.open().
Optional
flags: string | numberOptional
mode: string | numberSimilar to .writeFileSync(), except that if the parent directory does not exist, it will be created automatically.
Optional
options: null | string | { encoding?: null | string; flag?: string | number; mode?: string | number }Similar to .writeJSONSync(), except that if the parent directory does not exist, it will be created automatically.
Optional
options: null | string | { EOL?: "\n" | "\r\n"; encoding?: null | string; flag?: string | number; mode?: string | number; replacer?: null | (string | number)[] | ((this: any, key: string, value: any) => any); spaces?: string | number }Roughly same as fs.readFileSync()
, but no need to specify the path.
Synchronously reads the entire contents of a file.
If no encoding is specified (using options.encoding), the data is returned as a
If options is a string, then it specifies the encoding.
options.encoding
Default: nulloptions.flag
See support of file system flags. Default: 'r'Optional
options: null | { encoding?: null; flag?: string | number }Optional
options: null | string | { encoding?: null | string; flag?: string | number }Similar to .readFileSync()
, but guaranteed to return a string, use UTF-8 by
default.
Synchronously reads the entire contents of a file.
Optional
options: null | BufferEncoding | { encoding?: null | BufferEncoding; flag?: string | number }if options is a string, then it specifies the encoding.
options.encoding
Default: 'utf8'options.flag
See support of file system flags. Default: 'r'Synchronously reads a JSON file and then parses it into an object.
If options is a string, then it specifies the encoding.
options.encoding
Default: 'utf8'options.flag
See support of file system flags. Default: 'r'Optional
options: null | BufferEncoding | { encoding?: null | BufferEncoding; flag?: string | number }Execute the given function with the original content of the file as input, and the returned string will become the new content of the file.
Optional
options: null | BufferEncoding | { encoding?: null | BufferEncoding }If options is a string, then it specifies the encoding.
options.encoding
Default: 'utf8'Synchronously update the json object of the file.
accepts a object paresd from the JSON file, can return a new object or undefined (in that case, original object is used) to overwrite the file.
Optional
options: null | BufferEncoding | { encoding?: null | BufferEncoding }If options is a string, then it specifies the encoding.
options.encoding
Default: 'utf8'Roughly same as fs.writeFileSync()
, but no need to specify the path.
Synchronously writes data to a file, replacing the file if it already exists.
can be a string, a
Optional
options: null | string | { encoding?: null | string; flag?: string | number; mode?: string | number }If options is a string, then it specifies the encoding.
options.encoding
Default: 'utf8'options.mode
Default: 0o666options.flag
See support of file system flags. Default: 'w'.Synchronously writes an object to a JSON file.
Optional
options: null | string | { EOL?: "\n" | "\r\n"; encoding?: null | string; flag?: string | number; mode?: string | number; replacer?: null | (string | number)[] | ((this: any, key: string, value: any) => any); spaces?: string | number }a string to specify the encoding, or an object:
options.EOL
: set end-of-line character. Default: '\n'.options.replacer
: passed to JSON.stringify(). A function that alters the behavior
of the stringification process, or an array of strings or numbers naming properties
of value that should be included in the output. If replacer is null or not provided,
all properties of the object are included in the resulting JSON string.options.spaces
: passed to JSON.stringify(). A string or number used to insert
white space (including indentation, line break characters, etc.) into the output
JSON string for readability purposes.options.encoding
Default: 'utf8'options.mode
Default: 0o666options.flag
See support of file system flags. Default: 'w'.Similar to fs.cpSync(), except that the default value of options.recursive
is true.
Synchronously copies a file or directory to dest, including subdirectories and files when copying a directory.
destination path wrapped in PathNice
destination path to copy to.
Optional
options: { dereference?: null | boolean; errorOnExist?: null | boolean; filter?: null | ((src: string, dest: string) => boolean); force?: null | boolean; preserveTimestamps?: null | boolean; recursive?: null | boolean; verbatimSymlinks?: null | boolean }options.force
: overwrite existing file or directory. The copy operation will
ignore errors if you set this to false and the destination exists. Use the
errorOnExist
option to change this behavior. Default: true.
options.dereference
: dereference symlinks. Default: false.options.errorOnExist
: when force is false, and the destination exists, throw an
error. Default: false.options.filter
: Function to filter copied files/directories. Return true to copy
the item, false to ignore it. Default: undefined.options.preserveTimestamps
: When true timestamps from src will be preserved.
Default: false.options.recursive
: copy directories recursively. Default: trueoptions.verbatimSymlinks
: When true, path resolution for symlinks will be
skipped. Default: falseOptional
dereference?: null | booleanOptional
errorOptional
filter?: null | ((src: string, dest: string) => boolean)Optional
force?: null | booleanOptional
preserveOptional
recursive?: null | booleanOptional
verbatimSynchronously removes a file or directory. The directory can have contents. If the path does not exist, silently does nothing.
original path wrapped in Promise
Synchronously ensures that a directory is empty. Deletes directory contents if the directory is not empty. If the directory does not exist, it is created. The directory itself is not deleted.
original path wrapped in PathNice
Synchronously moves a file or directory to dest, even across devices, including subdirectories and files when moving a directory.
destination path wrapped in PathNice
destination to move to. Note: When src is a file, dest must be a file and when src is a directory, dest must be a directory.
Optional
options: { overwrite?: null | boolean }options.overwrite: overwrite existing file or directory. Default: false
Optional
overwrite?: null | booleanSynchronously removes a file or directory. The directory can have contents. If the path does not exist, silently does nothing.
original path wrapped in Promise
Synchronously ensures that a directory is empty. Deletes directory contents if the directory is not empty. If the directory does not exist, it is created. The directory itself is not deleted.
original path wrapped in PathNice
Asynchronously ensures that the directory exists. If the directory structure does not exist, it is created.
original path wrapped in PathNice
Optional
options: { mode?: string | number }options.mode: mode of the newly created directory. Default: 0o777
Optional
mode?: string | numberSynchronously ensures that the file exists. If the file that is requested to be created is in directories that do not exist, these directories are created. If the file already exists, it is NOT MODIFIED.
original path wrapped in PathNice
Optional
options: { dirMode?: string | number; fileMode?: string | number }options.fileMode: mode of the newly created file. Default: 0o777
0o777
Optional
dirOptional
fileNote: It is recommended to use isFile()
, isDir()
, etc to indicate the type of
file you want to check.
Synchronously check whether the path exists.
Synchronously check whether the path exists and is a directory.
Optional
followlink: booleanwhen true, if the path is a link, follows it. Default: false
Synchronously check whether the path exists and is an empty directory.
Note: if the path is inaccessible or not a directory, it also returns false.
Optional
followlink: booleanwhen true, if the path is a link, follows it. Default: false
Synchronously check whether the path exists and is a file.
Optional
followlink: booleanwhen true, if the path is a link, follows it. Default: false
Synchronously check whether the path exists and is a symbolic link.
Synchronously List all directories and files under the folder, return an object
{ dirs: PathNiceArr; files: PathNiceArr }
.
dirs
: subdirectories, not including the current folderfiles
: files and others (e.g. device, FIFO, socket, etc). If followLinks
is
false, it also contains links.The paths wrapped in the returned PathNice
object are all absolute paths, so
they can be used directly for .readFile()
, .writeFile()
, .copy()
, .move()
,
etc. Use .toRelative(dir)
to get the relative path.
const { dirs, files } = path('./').lsSync();
await Promise.all(
files
.filter(f => f.ext() === '.json')
.map(async f => {
await f.updateJSON(json => { json.timestamp = Date.now() });
await f.copy(f.dirname('../backup'));
})
);
await dirs.remove();
Optional
recursive: booleanwhether to list file recursively. Default: false
Optional
followLinks: booleanwhether to follow links under the folder. Default: false
Roughly same as fs.readdirSync()
, but no need to specify the path.
Reads the contents of a directory.
The optional options argument can be a string specifying an encoding, or an object
with an encoding property specifying the character encoding to use for the
filenames. If the encoding is set to 'buffer', the filenames returned will be
passed as
If options.withFileTypes is set to true, the resolved array will contain <fs.Dirent> objects.
try {
const files = path('path/to/dir').readdirSync();
for (const file of files)
console.log(file);
} catch (err) {
console.error(err);
}
Optional
options: null | BufferEncoding | { encoding?: null | BufferEncoding; withFileTypes?: false }a string to specify the encoding, or an object:
options.encoding
Default: 'utf8'options.withFileTypes
Default: falseOptional
options: string | { encoding: string; withFileTypes?: false }Optional
encoding?: null | BufferEncodingSynchronous chmod(2) - Change permissions of a file.
A file mode. If a string is passed, it is parsed as an octal integer.
Synchronous chown(2) - Change ownership of a file.
Synchronously gets the file mode.
Synchronously gets the uid and gid of the file owner.
Synchronously gets the file size.
Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links.
Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
Optional
options: undefinedOptional
options: StatSyncOptions & { bigint?: false; throwIfNoEntry: false }Optional
options: StatSyncOptions & { bigint: true; throwIfNoEntry: false }Optional
options: StatSyncOptions & { bigint?: false }Optional
options: StatSyncOptions & { bigint: true }Optional
options: StatSyncOptions & { bigint: boolean; throwIfNoEntry?: false }Optional
options: StatSyncOptionsSynchronous lstat(2) - Get file status. Does not dereference symbolic links.
Optional
options: undefinedOptional
options: StatSyncOptions & { bigint?: false; throwIfNoEntry: false }Optional
options: StatSyncOptions & { bigint: true; throwIfNoEntry: false }Optional
options: StatSyncOptions & { bigint?: false }Optional
options: StatSyncOptions & { bigint: true }Optional
options: StatSyncOptions & { bigint: boolean; throwIfNoEntry?: false }Optional
options: StatSyncOptionsReturns raw path string.
Returns raw path string.
Generated using TypeDoc
A PathNice object is a wrapper of the raw path string, so that the path can be easily used to generate additional paths or manipulate files.