Interface PathNice<T>

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.

Type Parameters

  • T = unknown

Hierarchy

  • _PathNice<T>
    • PathNice

Properties

raw: string

Path related Accessors

  • Alias for .dirname() .

    Return the path to the parent directory.

    Example

    $ path('/usr/local/bin').parent.raw
    '/usr/local' // on POSIX

    $ path('C:\\Users\\fuu').parent.raw
    'C:\\Users' // on Windows

    Returns PathNice<unknown>

Path related Methods

  • dirname(newDirname?: string | PathNice<unknown> | ((oldDirname: string) => string)): PathNice<unknown>
  • 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.

    Example

    $ 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

    Parameters

    • Optional newDirname: string | PathNice<unknown> | ((oldDirname: string) => string)

    Returns PathNice<unknown>

  • ext(): string
  • ext(newExt: null | string | ((oldExt: string) => string)): PathNice<unknown>
  • 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.

    Example

    $ 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

    Returns string

  • Parameters

    • newExt: null | string | ((oldExt: string) => string)

    Returns PathNice<unknown>

  • filename(): string
  • filename(newFilename: string | ((oldFilename: string) => string)): PathNice<unknown>
  • 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.

    Example

    $ 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

    Returns string

  • Parameters

    • newFilename: string | ((oldFilename: string) => string)

    Returns PathNice<unknown>

  • isAbsolute(): boolean
  • Determine whether path is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.

    Example

    // 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

    Returns boolean

  • Join this path with all arguments together and normalize the resulting path.

    Example

    $ 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

    Parameters

    • Rest ...paths: (string | PathNice<unknown>)[]

    Returns PathNice<unknown>

  • Return an object whose properties represent significant elements of the path.

    Example

    // on POSIX
    ┌─────────────────────┬────────────┐
    dirbase
    ├──────┐ ├──────┬─────┤
    root │ │ nameext
    " / 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
    ┌─────────────────────┬────────────┐
    dirbase
    ├──────┐ ├──────┬─────┤
    root │ │ nameext
    " 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'

    Returns ParsedPathNice

  • postfix(postfix: string): PathNice<unknown>
  • Add a postfix to the end of the path.

    This will only modifiy the path string and will not actually rename the file.

    Example

    $ 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

    Parameters

    • postfix: string

    Returns PathNice<unknown>

  • postfixBeforeExt(postfix: string): PathNice<unknown>
  • 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.

    Example

    $ path('path-nice/tsconfig.json').postfixBeforeExt('.base').raw
    'path-nice/tsconfig.base.json' // on POSIX
    'path-nice\\tsconfig.base.json' // on Windows

    Parameters

    • postfix: string

    Returns PathNice<unknown>

  • prefixFilename(prefix: string): PathNice<unknown>
  • 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.

    Example

    $ path('data/January').prefixFilename('2021-').raw
    'data/2021-January' // on POSIX
    'data\\2021-January' // on Windows

    Parameters

    • prefix: string

    Returns PathNice<unknown>

  • Asynchronously computes the canonical pathname by resolving ., .., and symbolic links.

    Returns Promise<PathNice<unknown>>

  • separator(): "/" | "\\" | "none" | "hybrid"
  • separator(forceSep: "/" | "\\"): PathNice<unknown>
  • 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.

    Example

    $ 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'

    Returns "/" | "\\" | "none" | "hybrid"

  • Parameters

    • forceSep: "/" | "\\"

    Returns PathNice<unknown>

  • Resolve the path to an absolute path, if it isn't now.

    Example

    $ 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'

    Parameters

    • 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.

    Returns PathNice<unknown>

  • 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.

    Example

    $ 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

    Parameters

    • Optional relativeTo: string | PathNice<unknown>

    Returns PathNice<unknown>

Read and write Methods

  • appendFile(data: string | Uint8Array, options?: null | BufferEncoding | { encoding?: null | string; flag?: string | number; mode?: string | number }): Promise<void>
  • Asynchronously append data to a file, creating the file if it does not yet exist.

    Parameters

    • data: string | Uint8Array

      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: 0o666
      • options.flag See support of file system flags. Default: 'a'.

    Returns Promise<void>

  • createReadStream(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 }): ReadStream
  • Roughly same as fs.createReadStream(), but no need to specify the path.

    See fs.createReadStream(path[, options]) for full document.

    Parameters

    • 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 }

    Returns ReadStream

  • createWriteStream(options?: string | { autoClose?: boolean; emitClose?: boolean; encoding?: string; fd?: number | FileHandle; flags?: string | number; fs?: any; mode?: string | number; start?: number }): WriteStream
  • Roughly same as fs.createWriteStream(), but no need to specify the path.

    See fs.createWriteStream(path[, options]) for full document.

    Parameters

    • Optional options: string | { autoClose?: boolean; emitClose?: boolean; encoding?: string; fd?: number | FileHandle; flags?: string | number; fs?: any; mode?: string | number; start?: number }

    Returns WriteStream

  • open(flags?: string | number, mode?: string | number): Promise<FileHandle>
  • 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.

    Parameters

    • Optional flags: string | number
    • Optional mode: string | number

    Returns Promise<FileHandle>

  • outputFile(data: any, options?: null | string | { encoding?: null | string; flag?: string | number; mode?: string | number; signal?: AbortSignal }): Promise<void>
  • Similar to .writeFile(), except that if the parent directory does not exist, it will be created automatically.

    Parameters

    • data: any
    • Optional options: null | string | { encoding?: null | string; flag?: string | number; mode?: string | number; signal?: AbortSignal }

    Returns Promise<void>

  • outputJSON(data: any, 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 }): Promise<void>
  • Similar to .writeJSON(), except that if the parent directory does not exist, it will be created automatically.

    Parameters

    • data: any
    • 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 }

    Returns Promise<void>

  • readFile(options?: null | { encoding?: null; flag?: string | number; signal?: AbortSignal }): Promise<Buffer>
  • readFile(options: BufferEncoding | { encoding: BufferEncoding; flag?: string | number; signal?: AbortSignal }): Promise<string>
  • readFile(options?: null | string | { encoding?: null | string; flag?: string | number; signal?: AbortSignal }): Promise<string | Buffer>
  • 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 object. Otherwise, the data will be a string.

    If options is a string, then it specifies the encoding.

    • options.encoding Default: null
    • options.flag See support of file system flags. Default: 'r'
    • options.signal allows aborting an in-progress readFile

    It 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.

    Parameters

    • Optional options: null | { encoding?: null; flag?: string | number; signal?: AbortSignal }

    Returns Promise<Buffer>

  • Parameters

    • options: BufferEncoding | { encoding: BufferEncoding; flag?: string | number; signal?: AbortSignal }

    Returns Promise<string>

  • Parameters

    • Optional options: null | string | { encoding?: null | string; flag?: string | number; signal?: AbortSignal }

    Returns Promise<string | Buffer>

  • readFileToString(options?: null | BufferEncoding | { encoding?: null | BufferEncoding; flag?: string | number; signal?: AbortSignal }): Promise<string>
  • Similar to .readFile(), but guaranteed to return a string, use UTF-8 by default.

    Asynchronously reads the entire contents of a file.

    Parameters

    • 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 readFile

      It 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.

    Returns Promise<string>

  • readJSON(options?: null | BufferEncoding | { encoding?: null | BufferEncoding; flag?: string | number }): Promise<any>
  • Asynchronously reads a JSON file and then parses it into an object.

    If options is a string, then it specifies the encoding.

    Parameters

    • Optional options: null | BufferEncoding | { encoding?: null | BufferEncoding; flag?: string | number }

    Returns Promise<any>

  • updateFileAsString(fn: ((original: string) => string | Promise<string>), options?: null | BufferEncoding | { encoding?: null | BufferEncoding }): Promise<void>
  • 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.

    Parameters

    • fn: ((original: string) => string | Promise<string>)

      can also return a Promise<string>

        • (original: string): string | Promise<string>
        • Parameters

          • original: string

          Returns string | Promise<string>

    • Optional options: null | BufferEncoding | { encoding?: null | BufferEncoding }

      If options is a string, then it specifies the encoding.

      • options.encoding Default: 'utf8'

    Returns Promise<void>

  • updateJSON(fn: ((original: any) => any), options?: null | BufferEncoding | { encoding?: null | BufferEncoding }): Promise<void>
  • Asynchronously update the json object of the file.

    Parameters

    • fn: ((original: any) => any)

      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.

        • (original: any): any
        • Parameters

          • original: any

          Returns any

    • Optional options: null | BufferEncoding | { encoding?: null | BufferEncoding }

      If options is a string, then it specifies the encoding.

      • options.encoding Default: 'utf8'

    Returns Promise<void>

  • writeFile(data: any, options?: null | string | { encoding?: null | string; flag?: string | number; mode?: string | number; signal?: AbortSignal }): Promise<void>
  • 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).

    Parameters

    • data: any

      can be a string, a , or, an object with an own (not inherited) toString function property. The encoding option is ignored if data is a buffer.

    • 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: 0o666
      • options.flag See support of file system flags. Default: 'w'.
      • options.signal allows aborting an in-progress writeFile

      It is possible to use an to cancel an writeFile(). Cancelation is "best effort", and some amount of data is likely still to be written.

      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.

    Returns Promise<void>

  • writeJSON(data: any, 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 }): Promise<void>
  • Asynchronously writes an object to a JSON file.

    Parameters

    • data: any
    • 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: 0o666
      • options.flag See support of file system flags. Default: 'w'.

    Returns Promise<void>

Copy, move and remove Methods

  • copy(dest: string | PathNice<unknown>, 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 }): Promise<PathNice<unknown>>
  • 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.

    Returns

    destination path wrapped in Promise

    Parameters

    • dest: string | PathNice<unknown>

      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: true
      • options.verbatimSymlinks: When true, path resolution for symlinks will be skipped. Default: false
      • Optional dereference?: null | boolean
      • Optional errorOnExist?: null | boolean
      • Optional filter?: null | ((src: string, dest: string) => boolean | Promise<boolean>)
      • Optional force?: null | boolean
      • Optional preserveTimestamps?: null | boolean
      • Optional recursive?: null | boolean
      • Optional verbatimSymlinks?: null | boolean

    Returns Promise<PathNice<unknown>>

  • Asynchronously removes a file or directory. The directory can have contents. If the path does not exist, silently does nothing.

    Returns

    original path wrapped in Promise

    Returns Promise<PathNice<unknown>>

  • 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.

    Returns

    original path wrapped in Promise

    Returns Promise<PathNice<unknown>>

  • move(dest: string | PathNice<unknown>, options?: { overwrite?: null | boolean }): Promise<PathNice<unknown>>
  • Asynchronously moves a file or directory to dest, even across devices, including subdirectories and files when moving a directory.

    Returns

    destination path wrapped in Promise

    Parameters

    • dest: string | PathNice<unknown>

      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 | boolean

    Returns Promise<PathNice<unknown>>

  • Asynchronously removes a file or directory. The directory can have contents. If the path does not exist, silently does nothing.

    Returns

    original path wrapped in Promise

    Returns Promise<PathNice<unknown>>

  • Asynchronous rename(2) - Change the name or location of a file or directory.

    Returns

    destination path wrapped in Promise

    Parameters

    • newPath: string | PathNice<unknown>

      A path to a file.

    Returns Promise<PathNice<unknown>>

Ensure Methods

  • 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.

    Returns

    original path wrapped in Promise

    Returns Promise<PathNice<unknown>>

  • ensureDir(options?: { mode?: string | number }): Promise<PathNice<unknown>>
  • Asynchronously ensures that the directory exists. If the directory structure does not exist, it is created.

    Returns

    original path wrapped in Promise

    Parameters

    • Optional options: { mode?: string | number }

      options.mode: mode of the newly created directory. Default: 0o777

      • Optional mode?: string | number

    Returns Promise<PathNice<unknown>>

  • ensureFile(options?: { dirMode?: string | number; fileMode?: string | number }): Promise<PathNice<unknown>>
  • Asynchronously 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.

    Returns

    original path wrapped in Promise

    Parameters

    • Optional options: { dirMode?: string | number; fileMode?: string | number }

      options.fileMode: mode of the newly created file. Default: 0o777

      • options.dirMode: mode of the newly created directory. Default: 0o777
      • Optional dirMode?: string | number
      • Optional fileMode?: string | number

    Returns Promise<PathNice<unknown>>

Is ... ? Methods

  • exists(): Promise<boolean>
  • Note: It is recommended to use isFile(), isDir(), etc to indicate the type of file you want to check.

    Asynchronously check whether the path exists.

    Returns Promise<boolean>

  • isDir(followlink?: boolean): Promise<boolean>
  • Asynchronously check whether the path exists and is a directory.

    Parameters

    • Optional followlink: boolean

      when true, if the path is a link, follows it. Default: false

    Returns Promise<boolean>

  • isEmptyDir(followlink?: boolean): Promise<boolean>
  • 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.

    Parameters

    • Optional followlink: boolean

      when true, if the path is a link, follows it. Default: false

    Returns Promise<boolean>

  • isFile(followlink?: boolean): Promise<boolean>
  • Asynchronously check whether the path exists and is a file.

    Parameters

    • Optional followlink: boolean

      when true, if the path is a link, follows it. Default: false

    Returns Promise<boolean>

  • Asynchronously check whether the path exists and is a symbolic link.

    Returns Promise<boolean>

List directory contents Methods

  • 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 folder
    • files: 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.

    Example

    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();

    Parameters

    • Optional recursive: boolean

      whether to list file recursively. Default: false

    • Optional followLinks: boolean

      whether to follow links under the folder. Default: false

    Returns Promise<{ dirs: PathNiceArr; files: PathNiceArr }>

  • readdir(options?: null | BufferEncoding | { encoding?: null | BufferEncoding; withFileTypes?: false }): Promise<string[]>
  • readdir(options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise<Buffer[]>
  • readdir(options?: string | { encoding: string; withFileTypes?: false }): Promise<string[] | Buffer[]>
  • readdir(options: { encoding?: null | BufferEncoding; withFileTypes: true }): Promise<Dirent[]>
  • 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 objects.

    If options.withFileTypes is set to true, the resolved array will contain <fs.Dirent> objects.

    Example

    try {
    const files = await path('path/to/dir').readdir();
    for (const file of files)
    console.log(file);
    } catch (err) {
    console.error(err);
    }

    Parameters

    • 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: false

    Returns Promise<string[]>

  • Parameters

    • options: "buffer" | { encoding: "buffer"; withFileTypes?: false }

    Returns Promise<Buffer[]>

  • Parameters

    • Optional options: string | { encoding: string; withFileTypes?: false }

    Returns Promise<string[] | Buffer[]>

  • Parameters

    • options: { encoding?: null | BufferEncoding; withFileTypes: true }
      • Optional encoding?: null | BufferEncoding
      • withFileTypes: true

    Returns Promise<Dirent[]>

Watch Methods

  • unwatchFile(listener?: ((curr: Stats, prev: Stats) => void)): void
  • Roughly 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.

    Parameters

    • Optional listener: ((curr: Stats, prev: Stats) => void)
        • (curr: Stats, prev: Stats): void
        • Parameters

          • curr: Stats
          • prev: Stats

          Returns void

    Returns void

  • watch(options: "buffer" | WatchOptions & { encoding: "buffer" }, listener?: WatchListener<Buffer>): FSWatcher
  • watch(options?: null | BufferEncoding | WatchOptions, listener?: WatchListener<string>): FSWatcher
  • watch(options: string | WatchOptions, listener?: WatchListener<string | Buffer>): FSWatcher
  • watch(listener?: WatchListener<string>): FSWatcher
  • 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.

    Parameters

    • options: "buffer" | WatchOptions & { encoding: "buffer" }
    • Optional listener: WatchListener<Buffer>

    Returns FSWatcher

  • Parameters

    • Optional options: null | BufferEncoding | WatchOptions
    • Optional listener: WatchListener<string>

    Returns FSWatcher

  • Parameters

    • options: string | WatchOptions
    • Optional listener: WatchListener<string | Buffer>

    Returns FSWatcher

  • Parameters

    • Optional listener: WatchListener<string>

    Returns FSWatcher

  • watchFile(options: undefined | WatchFileOptions & { bigint?: false }, listener: ((curr: Stats, prev: Stats) => void)): StatWatcher
  • watchFile(options: undefined | WatchFileOptions & { bigint: true }, listener: ((curr: BigIntStats, prev: BigIntStats) => void)): StatWatcher
  • watchFile(listener: ((curr: Stats, prev: Stats) => void)): StatWatcher
  • 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

    Parameters

    • options: undefined | WatchFileOptions & { bigint?: false }
    • listener: ((curr: Stats, prev: Stats) => void)
        • (curr: Stats, prev: Stats): void
        • Parameters

          • curr: Stats
          • prev: Stats

          Returns void

    Returns StatWatcher

  • Parameters

    • options: undefined | WatchFileOptions & { bigint: true }
    • listener: ((curr: BigIntStats, prev: BigIntStats) => void)
        • (curr: BigIntStats, prev: BigIntStats): void
        • Parameters

          • curr: BigIntStats
          • prev: BigIntStats

          Returns void

    Returns StatWatcher

  • Parameters

    • listener: ((curr: Stats, prev: Stats) => void)
        • (curr: Stats, prev: Stats): void
        • Parameters

          • curr: Stats
          • prev: Stats

          Returns void

    Returns StatWatcher

  • watchWithChokidar(options?: WatchOptions & { forceEvenDifferentFS?: boolean }): FSWatcher
  • 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.

    Parameters

    • Optional options: WatchOptions & { forceEvenDifferentFS?: boolean }

    Returns FSWatcher

File info Methods

  • chmod(mode: string | number): Promise<void>
  • Asynchronous chmod(2) - Change permissions of a file.

    Parameters

    • mode: string | number

      A file mode. If a string is passed, it is parsed as an octal integer.

    Returns Promise<void>

  • chown(uid: number, gid: number): Promise<void>
  • Asynchronous chown(2) - Change ownership of a file.

    Parameters

    • uid: number
    • gid: number

    Returns Promise<void>

  • fileMode(): Promise<number>
  • Asynchronously gets the file mode.

    Returns Promise<number>

  • fileOwner(): Promise<{ gid: number; uid: number }>
  • Asynchronously gets the uid and gid of the file owner.

    Returns Promise<{ gid: number; uid: number }>

  • fileSize(): Promise<{ B: number; GB: number; KB: number; MB: number; PB: number; TB: number }>
  • Asynchronously gets the file size.

    Returns Promise<{ B: number; GB: number; KB: number; MB: number; PB: number; TB: number }>

  • lchown(uid: number, gid: number): Promise<void>
  • Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links.

    Parameters

    • uid: number
    • gid: number

    Returns Promise<void>

  • lstat(options?: StatOptions & { bigint?: false }): Promise<Stats>
  • lstat(options: StatOptions & { bigint: true }): Promise<BigIntStats>
  • lstat(options?: StatOptions): Promise<Stats | BigIntStats>
  • Asynchronous lstat(2) - Get file status. Does not dereference symbolic links.

    Parameters

    • Optional options: StatOptions & { bigint?: false }

    Returns Promise<Stats>

  • Parameters

    • options: StatOptions & { bigint: true }

    Returns Promise<BigIntStats>

  • Parameters

    • Optional options: StatOptions

    Returns Promise<Stats | BigIntStats>

  • stat(opts?: StatOptions & { bigint?: false }): Promise<Stats>
  • stat(opts: StatOptions & { bigint: true }): Promise<BigIntStats>
  • stat(opts?: StatOptions): Promise<Stats | BigIntStats>
  • Asynchronous stat(2) - Get file status.

    Parameters

    • Optional opts: StatOptions & { bigint?: false }

    Returns Promise<Stats>

  • Parameters

    • opts: StatOptions & { bigint: true }

    Returns Promise<BigIntStats>

  • Parameters

    • Optional opts: StatOptions

    Returns Promise<Stats | BigIntStats>

Read and write Sync Methods

  • appendFileSync(data: string | Uint8Array, options?: null | BufferEncoding | { encoding?: null | string; flag?: string | number; mode?: string | number }): void
  • Synchronously append data to a file, creating the file if it does not yet exist.

    Parameters

    • data: string | Uint8Array

      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: 0o666
      • options.flag See support of file system flags. Default: 'a'.

    Returns void

  • openSync(flags?: string | number, mode?: string | number): number
  • 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().

    Parameters

    • Optional flags: string | number
    • Optional mode: string | number

    Returns number

  • outputFileSync(data: any, options?: null | string | { encoding?: null | string; flag?: string | number; mode?: string | number }): void
  • Similar to .writeFileSync(), except that if the parent directory does not exist, it will be created automatically.

    Parameters

    • data: any
    • Optional options: null | string | { encoding?: null | string; flag?: string | number; mode?: string | number }

    Returns void

  • outputJSONSync(data: any, 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 }): void
  • Similar to .writeJSONSync(), except that if the parent directory does not exist, it will be created automatically.

    Parameters

    • data: any
    • 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 }

    Returns void

  • readFileSync(options?: null | { encoding?: null; flag?: string | number }): Buffer
  • readFileSync(options: BufferEncoding | { encoding: BufferEncoding; flag?: string | number }): string
  • readFileSync(options?: null | string | { encoding?: null | string; flag?: string | number }): string | Buffer
  • 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 object. Otherwise, the data will be a string.

    If options is a string, then it specifies the encoding.

    Parameters

    • Optional options: null | { encoding?: null; flag?: string | number }

    Returns Buffer

  • Parameters

    • options: BufferEncoding | { encoding: BufferEncoding; flag?: string | number }

    Returns string

  • Parameters

    • Optional options: null | string | { encoding?: null | string; flag?: string | number }

    Returns string | Buffer

  • readFileToStringSync(options?: null | BufferEncoding | { encoding?: null | BufferEncoding; flag?: string | number }): string
  • Similar to .readFileSync(), but guaranteed to return a string, use UTF-8 by default.

    Synchronously reads the entire contents of a file.

    Parameters

    • Optional options: null | BufferEncoding | { encoding?: null | BufferEncoding; flag?: string | number }

      if options is a string, then it specifies the encoding.

    Returns string

  • readJSONSync(options?: null | BufferEncoding | { encoding?: null | BufferEncoding; flag?: string | number }): any
  • Synchronously reads a JSON file and then parses it into an object.

    If options is a string, then it specifies the encoding.

    Parameters

    • Optional options: null | BufferEncoding | { encoding?: null | BufferEncoding; flag?: string | number }

    Returns any

  • updateFileAsStringSync(fn: ((original: string) => string), options?: null | BufferEncoding | { encoding?: null | BufferEncoding }): void
  • 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.

    Parameters

    • fn: ((original: string) => string)
        • (original: string): string
        • Parameters

          • original: string

          Returns string

    • Optional options: null | BufferEncoding | { encoding?: null | BufferEncoding }

      If options is a string, then it specifies the encoding.

      • options.encoding Default: 'utf8'

    Returns void

  • updateJSONSync(fn: ((original: any) => any), options?: null | BufferEncoding | { encoding?: null | BufferEncoding }): void
  • Synchronously update the json object of the file.

    Parameters

    • fn: ((original: any) => any)

      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.

        • (original: any): any
        • Parameters

          • original: any

          Returns any

    • Optional options: null | BufferEncoding | { encoding?: null | BufferEncoding }

      If options is a string, then it specifies the encoding.

      • options.encoding Default: 'utf8'

    Returns void

  • writeFileSync(data: any, options?: null | string | { encoding?: null | string; flag?: string | number; mode?: string | number }): void
  • 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.

    Parameters

    • data: any

      can be a string, a , or, an object with an own (not inherited) toString function property. The encoding option is ignored if data is a buffer.

    • Optional options: null | string | { encoding?: null | string; flag?: string | number; mode?: string | number }

      If options is a string, then it specifies the encoding.

    Returns void

  • writeJSONSync(data: any, 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 }): void
  • Synchronously writes an object to a JSON file.

    Parameters

    • data: any
    • 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: 0o666
      • options.flag See support of file system flags. Default: 'w'.

    Returns void

Copy, move and remove Sync Methods

  • copySync(dest: string | PathNice<unknown>, 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 }): PathNice<unknown>
  • 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.

    Returns

    destination path wrapped in PathNice

    Parameters

    • dest: string | PathNice<unknown>

      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: true
      • options.verbatimSymlinks: When true, path resolution for symlinks will be skipped. Default: false
      • Optional dereference?: null | boolean
      • Optional errorOnExist?: null | boolean
      • Optional filter?: null | ((src: string, dest: string) => boolean)
      • Optional force?: null | boolean
      • Optional preserveTimestamps?: null | boolean
      • Optional recursive?: null | boolean
      • Optional verbatimSymlinks?: null | boolean

    Returns PathNice<unknown>

  • Synchronously removes a file or directory. The directory can have contents. If the path does not exist, silently does nothing.

    Returns

    original path wrapped in Promise

    Returns PathNice<unknown>

  • 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.

    Returns

    original path wrapped in PathNice

    Returns PathNice<unknown>

  • moveSync(dest: string | PathNice<unknown>, options?: { overwrite?: null | boolean }): PathNice<unknown>
  • Synchronously moves a file or directory to dest, even across devices, including subdirectories and files when moving a directory.

    Returns

    destination path wrapped in PathNice

    Parameters

    • dest: string | PathNice<unknown>

      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 | boolean

    Returns PathNice<unknown>

  • Synchronously removes a file or directory. The directory can have contents. If the path does not exist, silently does nothing.

    Returns

    original path wrapped in Promise

    Returns PathNice<unknown>

  • Synchronous rename(2) - Change the name or location of a file or directory.

    Returns

    destination path wrapped in PathNice

    Parameters

    • newPath: string | PathNice<unknown>

      A path to a file.

    Returns PathNice<unknown>

Ensure Sync Methods

  • 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.

    Returns

    original path wrapped in PathNice

    Returns PathNice<unknown>

  • ensureDirSync(options?: { mode?: string | number }): PathNice<unknown>
  • Asynchronously ensures that the directory exists. If the directory structure does not exist, it is created.

    Returns

    original path wrapped in PathNice

    Parameters

    • Optional options: { mode?: string | number }

      options.mode: mode of the newly created directory. Default: 0o777

      • Optional mode?: string | number

    Returns PathNice<unknown>

  • ensureFileSync(options?: { dirMode?: string | number; fileMode?: string | number }): PathNice<unknown>
  • Synchronously 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.

    Returns

    original path wrapped in PathNice

    Parameters

    • Optional options: { dirMode?: string | number; fileMode?: string | number }

      options.fileMode: mode of the newly created file. Default: 0o777

      • options.dirMode: mode of the newly created directory. Default: 0o777
      • Optional dirMode?: string | number
      • Optional fileMode?: string | number

    Returns PathNice<unknown>

Is ... ? Sync Methods

  • existsSync(): boolean
  • Note: It is recommended to use isFile(), isDir(), etc to indicate the type of file you want to check.

    Synchronously check whether the path exists.

    Returns boolean

  • isDirSync(followlink?: boolean): boolean
  • Synchronously check whether the path exists and is a directory.

    Parameters

    • Optional followlink: boolean

      when true, if the path is a link, follows it. Default: false

    Returns boolean

  • isEmptyDirSync(followlink?: boolean): boolean
  • 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.

    Parameters

    • Optional followlink: boolean

      when true, if the path is a link, follows it. Default: false

    Returns boolean

  • isFileSync(followlink?: boolean): boolean
  • Synchronously check whether the path exists and is a file.

    Parameters

    • Optional followlink: boolean

      when true, if the path is a link, follows it. Default: false

    Returns boolean

  • isSymbolicLinkSync(): boolean
  • Synchronously check whether the path exists and is a symbolic link.

    Returns boolean

List directory contents Sync Methods

  • Synchronously List all directories and files under the folder, return an object { dirs: PathNiceArr; files: PathNiceArr }.

    • dirs: subdirectories, not including the current folder
    • files: 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.

    Example

    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();

    Parameters

    • Optional recursive: boolean

      whether to list file recursively. Default: false

    • Optional followLinks: boolean

      whether to follow links under the folder. Default: false

    Returns { dirs: PathNiceArr; files: PathNiceArr }

  • readdirSync(options?: null | BufferEncoding | { encoding?: null | BufferEncoding; withFileTypes?: false }): string[]
  • readdirSync(options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Buffer[]
  • readdirSync(options?: string | { encoding: string; withFileTypes?: false }): string[] | Buffer[]
  • readdirSync(options: { encoding?: null | BufferEncoding; withFileTypes: true }): Dirent[]
  • 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 objects.

    If options.withFileTypes is set to true, the resolved array will contain <fs.Dirent> objects.

    Example

    try {
    const files = path('path/to/dir').readdirSync();
    for (const file of files)
    console.log(file);
    } catch (err) {
    console.error(err);
    }

    Parameters

    • 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: false

    Returns string[]

  • Parameters

    • options: "buffer" | { encoding: "buffer"; withFileTypes?: false }

    Returns Buffer[]

  • Parameters

    • Optional options: string | { encoding: string; withFileTypes?: false }

    Returns string[] | Buffer[]

  • Parameters

    • options: { encoding?: null | BufferEncoding; withFileTypes: true }
      • Optional encoding?: null | BufferEncoding
      • withFileTypes: true

    Returns Dirent[]

File info Sync Methods

  • chmodSync(mode: string | number): void
  • Synchronous chmod(2) - Change permissions of a file.

    Parameters

    • mode: string | number

      A file mode. If a string is passed, it is parsed as an octal integer.

    Returns void

  • chownSync(uid: number, gid: number): void
  • Synchronous chown(2) - Change ownership of a file.

    Parameters

    • uid: number
    • gid: number

    Returns void

  • fileModeSync(): number
  • Synchronously gets the file mode.

    Returns number

  • fileOwnerSync(): { gid: number; uid: number }
  • Synchronously gets the uid and gid of the file owner.

    Returns { gid: number; uid: number }

    • gid: number
    • uid: number
  • fileSizeSync(): { B: number; GB: number; KB: number; MB: number; PB: number; TB: number }
  • Synchronously gets the file size.

    Returns { B: number; GB: number; KB: number; MB: number; PB: number; TB: number }

    • B: number
    • GB: number
    • KB: number
    • MB: number
    • PB: number
    • TB: number
  • lchownSync(uid: number, gid: number): void
  • Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links.

    Parameters

    • uid: number
    • gid: number

    Returns void

  • lstatSync(options?: undefined): Stats
  • lstatSync(options?: StatSyncOptions & { bigint?: false; throwIfNoEntry: false }): undefined | Stats
  • lstatSync(options?: StatSyncOptions & { bigint: true; throwIfNoEntry: false }): undefined | BigIntStats
  • lstatSync(options?: StatSyncOptions & { bigint?: false }): Stats
  • lstatSync(options?: StatSyncOptions & { bigint: true }): BigIntStats
  • lstatSync(options?: StatSyncOptions & { bigint: boolean; throwIfNoEntry?: false }): Stats | BigIntStats
  • lstatSync(options?: StatSyncOptions): undefined | Stats | BigIntStats
  • Synchronous lstat(2) - Get file status. Does not dereference symbolic links.

    Parameters

    • Optional options: undefined

    Returns Stats

  • Parameters

    • Optional options: StatSyncOptions & { bigint?: false; throwIfNoEntry: false }

    Returns undefined | Stats

  • Parameters

    • Optional options: StatSyncOptions & { bigint: true; throwIfNoEntry: false }

    Returns undefined | BigIntStats

  • Parameters

    • Optional options: StatSyncOptions & { bigint?: false }

    Returns Stats

  • Parameters

    • Optional options: StatSyncOptions & { bigint: true }

    Returns BigIntStats

  • Parameters

    • Optional options: StatSyncOptions & { bigint: boolean; throwIfNoEntry?: false }

    Returns Stats | BigIntStats

  • Parameters

    • Optional options: StatSyncOptions

    Returns undefined | Stats | BigIntStats

  • statSync(options?: undefined): Stats
  • statSync(options?: StatSyncOptions & { bigint?: false; throwIfNoEntry: false }): undefined | Stats
  • statSync(options?: StatSyncOptions & { bigint: true; throwIfNoEntry: false }): undefined | BigIntStats
  • statSync(options?: StatSyncOptions & { bigint?: false }): Stats
  • statSync(options?: StatSyncOptions & { bigint: true }): BigIntStats
  • statSync(options?: StatSyncOptions & { bigint: boolean; throwIfNoEntry?: false }): Stats | BigIntStats
  • statSync(options?: StatSyncOptions): undefined | Stats | BigIntStats
  • Synchronous lstat(2) - Get file status. Does not dereference symbolic links.

    Parameters

    • Optional options: undefined

    Returns Stats

  • Parameters

    • Optional options: StatSyncOptions & { bigint?: false; throwIfNoEntry: false }

    Returns undefined | Stats

  • Parameters

    • Optional options: StatSyncOptions & { bigint: true; throwIfNoEntry: false }

    Returns undefined | BigIntStats

  • Parameters

    • Optional options: StatSyncOptions & { bigint?: false }

    Returns Stats

  • Parameters

    • Optional options: StatSyncOptions & { bigint: true }

    Returns BigIntStats

  • Parameters

    • Optional options: StatSyncOptions & { bigint: boolean; throwIfNoEntry?: false }

    Returns Stats | BigIntStats

  • Parameters

    • Optional options: StatSyncOptions

    Returns undefined | Stats | BigIntStats

Methods

  • toString(): string
  • Returns raw path string.

    Returns string

  • valueOf(): string
  • Returns raw path string.

    Returns string

Generated using TypeDoc