Interface FileSystem

Minimal filesystem type Based on the required operations from fs/promises Implement this with platform-specific filesystem

Hierarchy

  • FileSystem

Properties

Properties

constants: typeof constants
promises: {
    access: ((path, mode?) => Promise<void>);
    copyFile: ((src, dest, mode?) => Promise<void>);
    mkdir: {
        (path, options): Promise<string | undefined>;
        (path, options?): Promise<void>;
        (path, options?): Promise<string | undefined>;
    };
    mkdtemp: {
        (prefix, options?): Promise<string>;
        (prefix, options): Promise<Buffer>;
        (prefix, options?): Promise<string | Buffer>;
    };
    open: ((path, flags?, mode?) => Promise<FileHandle>);
    readFile: {
        (path, options?): Promise<Buffer>;
        (path, options): Promise<string>;
        (path, options?): Promise<string | Buffer>;
    };
    readdir: {
        (path, options?): Promise<string[]>;
        (path, options): Promise<Buffer[]>;
        (path, options?): Promise<string[] | Buffer[]>;
        (path, options): Promise<Dirent[]>;
    };
    rename: ((oldPath, newPath) => Promise<void>);
    rm: ((path, options?) => Promise<void>);
    rmdir: ((path, options?) => Promise<void>);
    stat: {
        (path, opts?): Promise<Stats>;
        (path, opts): Promise<BigIntStats>;
        (path, opts?): Promise<Stats | BigIntStats>;
    };
    writeFile: ((file, data, options?) => Promise<void>);
}

Type declaration

  • access: ((path, mode?) => Promise<void>)
      • (path, mode?): Promise<void>
      • Tests a user's permissions for the file or directory specified by path. The mode argument is an optional integer that specifies the accessibility checks to be performed. mode should be either the value fs.constants.F_OKor a mask consisting of the bitwise OR of any of fs.constants.R_OK,fs.constants.W_OK, and fs.constants.X_OK (e.g.fs.constants.W_OK | fs.constants.R_OK). Check File access constants for possible values of mode.

        If the accessibility check is successful, the promise is resolved with no value. If any of the accessibility checks fail, the promise is rejected with an Error object. The following example checks if the file/etc/passwd can be read and written by the current process.

        import { access, constants } from 'node:fs/promises';

        try {
        await access('/etc/passwd', constants.R_OK | constants.W_OK);
        console.log('can access');
        } catch {
        console.error('cannot access');
        }

        Using fsPromises.access() to check for the accessibility of a file before calling fsPromises.open() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.

        Parameters

        • path: PathLike
        • Optional mode: number

        Returns Promise<void>

        Fulfills with undefined upon success.

        Since

        v10.0.0

  • copyFile: ((src, dest, mode?) => Promise<void>)
      • (src, dest, mode?): Promise<void>
      • Asynchronously copies src to dest. By default, dest is overwritten if it already exists.

        No guarantees are made about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, an attempt will be made to remove the destination.

        import { copyFile, constants } from 'node:fs/promises';

        try {
        await copyFile('source.txt', 'destination.txt');
        console.log('source.txt was copied to destination.txt');
        } catch {
        console.error('The file could not be copied');
        }

        // By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
        try {
        await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
        console.log('source.txt was copied to destination.txt');
        } catch {
        console.error('The file could not be copied');
        }

        Parameters

        • src: PathLike

          source filename to copy

        • dest: PathLike

          destination filename of the copy operation

        • Optional mode: number

          Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE)

        Returns Promise<void>

        Fulfills with undefined upon success.

        Since

        v10.0.0

  • mkdir: {
        (path, options): Promise<string | undefined>;
        (path, options?): Promise<void>;
        (path, options?): Promise<string | undefined>;
    }
      • (path, options): Promise<string | undefined>
      • Asynchronously creates a directory.

        The optional options argument can be an integer specifying mode (permission and sticky bits), or an object with a mode property and a recursiveproperty indicating whether parent directories should be created. CallingfsPromises.mkdir() when path is a directory that exists results in a rejection only when recursive is false.

        import { mkdir } from 'node:fs/promises';

        try {
        const projectFolder = new URL('./test/project/', import.meta.url);
        const createDir = await mkdir(projectFolder, { recursive: true });

        console.log(`created ${createDir}`);
        } catch (err) {
        console.error(err.message);
        }

        Parameters

        • path: PathLike
        • options: MakeDirectoryOptions & {
              recursive: true;
          }

        Returns Promise<string | undefined>

        Upon success, fulfills with undefined if recursive is false, or the first directory path created if recursive is true.

        Since

        v10.0.0

      • (path, options?): Promise<void>
      • Asynchronous mkdir(2) - create a directory.

        Parameters

        • path: PathLike

          A path to a file. If a URL is provided, it must use the file: protocol.

        • Optional options: null | Mode | MakeDirectoryOptions & {
              recursive?: false;
          }

          Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777.

        Returns Promise<void>

      • (path, options?): Promise<string | undefined>
      • Asynchronous mkdir(2) - create a directory.

        Parameters

        • path: PathLike

          A path to a file. If a URL is provided, it must use the file: protocol.

        • Optional options: null | MakeDirectoryOptions | Mode

          Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777.

        Returns Promise<string | undefined>

  • mkdtemp: {
        (prefix, options?): Promise<string>;
        (prefix, options): Promise<Buffer>;
        (prefix, options?): Promise<string | Buffer>;
    }
      • (prefix, options?): Promise<string>
      • Creates a unique temporary directory. A unique directory name is generated by appending six random characters to the end of the provided prefix. Due to platform inconsistencies, avoid trailing X characters in prefix. Some platforms, notably the BSDs, can return more than six random characters, and replace trailing X characters in prefix with random characters.

        The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use.

        import { mkdtemp } from 'node:fs/promises';
        import { join } from 'node:path';
        import { tmpdir } from 'node:os';

        try {
        await mkdtemp(join(tmpdir(), 'foo-'));
        } catch (err) {
        console.error(err);
        }

        The fsPromises.mkdtemp() method will append the six randomly selected characters directly to the prefix string. For instance, given a directory/tmp, if the intention is to create a temporary directory within/tmp, theprefix must end with a trailing platform-specific path separator (require('node:path').sep).

        Parameters

        • prefix: string
        • Optional options: null | ObjectEncodingOptions | BufferEncoding

        Returns Promise<string>

        Fulfills with a string containing the file system path of the newly created temporary directory.

        Since

        v10.0.0

      • (prefix, options): Promise<Buffer>
      • Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.

        Parameters

        • prefix: string
        • options: BufferEncodingOption

          The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.

        Returns Promise<Buffer>

      • (prefix, options?): Promise<string | Buffer>
      • Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.

        Parameters

        • prefix: string
        • Optional options: null | ObjectEncodingOptions | BufferEncoding

          The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.

        Returns Promise<string | Buffer>

  • open: ((path, flags?, mode?) => Promise<FileHandle>)
      • (path, flags?, mode?): Promise<FileHandle>
      • 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

        • path: PathLike
        • Optional flags: string | number

          See support of file system flags``.

        • Optional mode: Mode

          Sets the file mode (permission and sticky bits) if the file is created.

        Returns Promise<FileHandle>

        Fulfills with a {FileHandle} object.

        Since

        v10.0.0

  • readFile: {
        (path, options?): Promise<Buffer>;
        (path, options): Promise<string>;
        (path, options?): Promise<string | Buffer>;
    }
      • (path, options?): Promise<Buffer>
      • Asynchronously reads the entire contents of a file.

        If no encoding is specified (using options.encoding), the data is returned as a Buffer object. Otherwise, the data will be a string.

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

        When the path is a directory, the behavior of fsPromises.readFile() is platform-specific. On macOS, Linux, and Windows, the promise will be rejected with an error. On FreeBSD, a representation of the directory's contents will be returned.

        An example of reading a package.json file located in the same directory of the running code:

        import { readFile } from 'node:fs/promises';
        try {
        const filePath = new URL('./package.json', import.meta.url);
        const contents = await readFile(filePath, { encoding: 'utf8' });
        console.log(contents);
        } catch (err) {
        console.error(err.message);
        }

        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 { readFile } from 'node:fs/promises';

        try {
        const controller = new AbortController();
        const { signal } = controller;
        const promise = readFile(fileName, { 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.

        Any specified FileHandle has to support reading.

        Parameters

        • path: FileHandle | PathLike

          filename or FileHandle

        • Optional options: null | {
              encoding?: null;
              flag?: OpenMode;
          } & Abortable

        Returns Promise<Buffer>

        Fulfills with the contents of the file.

        Since

        v10.0.0

      • (path, options): Promise<string>
      • Asynchronously reads the entire contents of a file.

        Parameters

        • path: FileHandle | PathLike

          A path to a file. If a URL is provided, it must use the file: protocol. If a FileHandle is provided, the underlying file will not be closed automatically.

        • options: BufferEncoding | {
              encoding: BufferEncoding;
              flag?: OpenMode;
          } & Abortable

          An object that may contain an optional flag. If a flag is not provided, it defaults to 'r'.

        Returns Promise<string>

      • (path, options?): Promise<string | Buffer>
      • Asynchronously reads the entire contents of a file.

        Parameters

        • path: FileHandle | PathLike

          A path to a file. If a URL is provided, it must use the file: protocol. If a FileHandle is provided, the underlying file will not be closed automatically.

        • Optional options: null | BufferEncoding | ObjectEncodingOptions & Abortable & {
              flag?: OpenMode;
          }

          An object that may contain an optional flag. If a flag is not provided, it defaults to 'r'.

        Returns Promise<string | Buffer>

  • readdir: {
        (path, options?): Promise<string[]>;
        (path, options): Promise<Buffer[]>;
        (path, options?): Promise<string[] | Buffer[]>;
        (path, options): Promise<Dirent[]>;
    }
      • (path, options?): Promise<string[]>
      • 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 Buffer objects.

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

        import { readdir } from 'node:fs/promises';

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

        Parameters

        • path: PathLike
        • Optional options: null | BufferEncoding | ObjectEncodingOptions & {
              recursive?: boolean;
              withFileTypes?: false;
          }

        Returns Promise<string[]>

        Fulfills with an array of the names of the files in the directory excluding '.' and '..'.

        Since

        v10.0.0

      • (path, options): Promise<Buffer[]>
      • Asynchronous readdir(3) - read a directory.

        Parameters

        • path: PathLike

          A path to a file. If a URL is provided, it must use the file: protocol.

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

          The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.

        Returns Promise<Buffer[]>

      • (path, options?): Promise<string[] | Buffer[]>
      • Asynchronous readdir(3) - read a directory.

        Parameters

        • path: PathLike

          A path to a file. If a URL is provided, it must use the file: protocol.

        • Optional options: null | BufferEncoding | ObjectEncodingOptions & {
              recursive?: boolean;
              withFileTypes?: false;
          }

          The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used.

        Returns Promise<string[] | Buffer[]>

      • (path, options): Promise<Dirent[]>
      • Asynchronous readdir(3) - read a directory.

        Parameters

        • path: PathLike

          A path to a file. If a URL is provided, it must use the file: protocol.

        • options: ObjectEncodingOptions & {
              recursive?: boolean;
              withFileTypes: true;
          }

          If called with withFileTypes: true the result data will be an array of Dirent.

        Returns Promise<Dirent[]>

  • rename: ((oldPath, newPath) => Promise<void>)
      • (oldPath, newPath): Promise<void>
      • Renames oldPath to newPath.

        Parameters

        • oldPath: PathLike
        • newPath: PathLike

        Returns Promise<void>

        Fulfills with undefined upon success.

        Since

        v10.0.0

  • rm: ((path, options?) => Promise<void>)
      • (path, options?): Promise<void>
      • Removes files and directories (modeled on the standard POSIX rm utility).

        Parameters

        • path: PathLike
        • Optional options: RmOptions

        Returns Promise<void>

        Fulfills with undefined upon success.

        Since

        v14.14.0

  • rmdir: ((path, options?) => Promise<void>)
      • (path, options?): Promise<void>
      • Removes the directory identified by path.

        Using fsPromises.rmdir() on a file (not a directory) results in the promise being rejected with an ENOENT error on Windows and an ENOTDIRerror on POSIX.

        To get a behavior similar to the rm -rf Unix command, use fsPromises.rm() with options { recursive: true, force: true }.

        Parameters

        • path: PathLike
        • Optional options: RmDirOptions

        Returns Promise<void>

        Fulfills with undefined upon success.

        Since

        v10.0.0

  • stat: {
        (path, opts?): Promise<Stats>;
        (path, opts): Promise<BigIntStats>;
        (path, opts?): Promise<Stats | BigIntStats>;
    }
      • (path, opts?): Promise<Stats>
      • Parameters

        • path: PathLike
        • Optional opts: StatOptions & {
              bigint?: false;
          }

        Returns Promise<Stats>

        Fulfills with the {fs.Stats} object for the given path.

        Since

        v10.0.0

      • (path, opts): Promise<BigIntStats>
      • Parameters

        • path: PathLike
        • opts: StatOptions & {
              bigint: true;
          }

        Returns Promise<BigIntStats>

      • (path, opts?): Promise<Stats | BigIntStats>
      • Parameters

        • path: PathLike
        • Optional opts: StatOptions

        Returns Promise<Stats | BigIntStats>

  • writeFile: ((file, data, options?) => Promise<void>)
      • (file, data, options?): Promise<void>
      • Asynchronously writes data to a file, replacing the file if it already exists.data can be a string, a buffer, an AsyncIterable, or an Iterable object.

        The encoding option is ignored if data is a buffer.

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

        The mode option only affects the newly created file. See fs.open() for more details.

        Any specified FileHandle has to support writing.

        It is unsafe to use fsPromises.writeFile() multiple times on the same file without waiting for the promise to be settled.

        Similarly to fsPromises.readFile - fsPromises.writeFile is a convenience method that performs multiple write calls internally to write the buffer passed to it. For performance sensitive code consider using fs.createWriteStream() or filehandle.createWriteStream().

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

        import { writeFile } from 'node:fs/promises';
        import { Buffer } from 'node: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 fs.writeFile performs.

        Parameters

        • file: FileHandle | PathLike

          filename or FileHandle

        • data: string | ArrayBufferView | Iterable<string | ArrayBufferView> | AsyncIterable<string | ArrayBufferView> | Stream
        • Optional options: null | BufferEncoding | ObjectEncodingOptions & {
              flag?: OpenMode;
              mode?: Mode;
          } & Abortable

        Returns Promise<void>

        Fulfills with undefined upon success.

        Since

        v10.0.0

Generated using TypeDoc