Spec-Zone.ru › Deno 2

fs

The node:fs module enables interacting with the file system in a way modeled on standard POSIX functions.

To use the promise-based APIs:

import * as fs from 'node:fs/promises';

To use the callback and sync APIs:

import * as fs from 'node:fs';

All file system operations have synchronous, callback, and promise-based forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).

Usage in Deno

import * as mod from "node:fs";

class Dir

implements AsyncIterable<Dirent>

Usage in Deno

import { Dir } from "node:fs";

A class representing a directory stream.

Created by opendir, opendirSync, or fsPromises.opendir().

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

try {
  const dir = await opendir('./');
  for await (const dirent of dir)
    console.log(dirent.name);
} catch (err) {
  console.error(err);
}

When using the async iterator, the fs.Dir object will be automatically closed after the iterator exits.

Properties

path: string
readonly

The read-only path of this directory as was provided to opendir,opendirSync, or fsPromises.opendir().

Methods

[Symbol.asyncIterator](): AsyncIterator<Dirent>

Asynchronously iterates over the directory via readdir(3) until all entries have been read.

close(): Promise<void>

Asynchronously close the directory's underlying resource handle. Subsequent reads will result in errors.

A promise is returned that will be fulfilled after the resource has been closed.

close(cb: NoParamCallback): void
closeSync(): void

Synchronously close the directory's underlying resource handle. Subsequent reads will result in errors.

read(): Promise<Dirent | null>

Asynchronously read the next directory entry via readdir(3) as an fs.Dirent.

A promise is returned that will be fulfilled with an fs.Dirent, or null if there are no more directory entries to read.

Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.

read(cb: (
err: ErrnoException | null,
dirEnt: Dirent | null,
) => void
): void
readSync(): Dirent | null

Synchronously read the next directory entry as an fs.Dirent. See the POSIX readdir(3) documentation for more detail.

If there are no more directory entries to read, null will be returned.

Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.


class Dirent

Usage in Deno

import { Dirent } from "node:fs";

A representation of a directory entry, which can be a file or a subdirectory within the directory, as returned by reading from an fs.Dir. The directory entry is a combination of the file name and file type pairs.

Additionally, when readdir or readdirSync is called with the withFileTypes option set to true, the resulting array is filled with fs.Dirent objects, rather than strings or Buffer s.

Properties

name: string

The file name that this fs.Dirent object refers to. The type of this value is determined by the options.encoding passed to readdir or readdirSync.

parentPath: string

The base path that this fs.Dirent object refers to.

path: string
deprecated

Alias for dirent.parentPath.

Methods

isBlockDevice(): boolean

Returns true if the fs.Dirent object describes a block device.

isCharacterDevice(): boolean

Returns true if the fs.Dirent object describes a character device.

isDirectory(): boolean

Returns true if the fs.Dirent object describes a file system directory.

isFIFO(): boolean

Returns true if the fs.Dirent object describes a first-in-first-out (FIFO) pipe.

isFile(): boolean

Returns true if the fs.Dirent object describes a regular file.

isSocket(): boolean

Returns true if the fs.Dirent object describes a socket.

isSymbolicLink(): boolean

Returns true if the fs.Dirent object describes a symbolic link.


class ReadStream

extends stream.Readable

Usage in Deno

import { ReadStream } from "node:fs";

Instances of fs.ReadStream are created and returned using the createReadStream function.

Properties

bytesRead: number

The number of bytes that have been read so far.

path: string | Buffer

The path to the file the stream is reading from as specified in the first argument to fs.createReadStream(). If path is passed as a string, thenreadStream.path will be a string. If path is passed as a Buffer, thenreadStream.path will be a Buffer. If fd is specified, thenreadStream.path will be undefined.

pending: boolean

This property is true if the underlying file has not been opened yet, i.e. before the 'ready' event is emitted.

Methods

addListener<K extends keyof ReadStreamEvents>(
event: K,
listener: ReadStreamEvents[K],
): this

events.EventEmitter

  1. open
  2. close
  3. ready
close(callback?: (err?: ErrnoException | null) => void): void
on<K extends keyof ReadStreamEvents>(
event: K,
listener: ReadStreamEvents[K],
): this
once<K extends keyof ReadStreamEvents>(
event: K,
listener: ReadStreamEvents[K],
): this
prependListener<K extends keyof ReadStreamEvents>(
event: K,
listener: ReadStreamEvents[K],
): this
prependOnceListener<K extends keyof ReadStreamEvents>(
event: K,
listener: ReadStreamEvents[K],
): this

class WriteStream

extends stream.Writable

Usage in Deno

import { WriteStream } from "node:fs";
  • Extends stream.Writable

Instances of fs.WriteStream are created and returned using the createWriteStream function.

Properties

bytesWritten: number

The number of bytes written so far. Does not include data that is still queued for writing.

path: string | Buffer

The path to the file the stream is writing to as specified in the first argument to createWriteStream. If path is passed as a string, thenwriteStream.path will be a string. If path is passed as a Buffer, thenwriteStream.path will be a Buffer.

pending: boolean

This property is true if the underlying file has not been opened yet, i.e. before the 'ready' event is emitted.

Methods

addListener<K extends keyof WriteStreamEvents>(
event: K,
listener: WriteStreamEvents[K],
): this

events.EventEmitter

  1. open
  2. close
  3. ready
close(callback?: (err?: ErrnoException | null) => void): void

Closes writeStream. Optionally accepts a callback that will be executed once the writeStreamis closed.

on<K extends keyof WriteStreamEvents>(
event: K,
listener: WriteStreamEvents[K],
): this
once<K extends keyof WriteStreamEvents>(
event: K,
listener: WriteStreamEvents[K],
): this
prependListener<K extends keyof WriteStreamEvents>(
event: K,
listener: WriteStreamEvents[K],
): this
prependOnceListener<K extends keyof WriteStreamEvents>(
event: K,
listener: WriteStreamEvents[K],
): this

function access

Usage in Deno

import { access } from "node:fs";

Overload 1

access(
path: PathLike,
mode: number | undefined,
callback: NoParamCallback,
): 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_OK or 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.

The final argument, callback, is a callback function that is invoked with a possible error argument. If any of the accessibility checks fail, the error argument will be an Error object. The following examples check if package.json exists, and if it is readable or writable.

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

const file = 'package.json';

// Check if the file exists in the current directory.
access(file, constants.F_OK, (err) => {
  console.log(`${file}${err ? 'does not exist' : 'exists'}`);
});

// Check if the file is readable.
access(file, constants.R_OK, (err) => {
  console.log(`${file}${err ? 'is not readable' : 'is readable'}`);
});

// Check if the file is writable.
access(file, constants.W_OK, (err) => {
  console.log(`${file}${err ? 'is not writable' : 'is writable'}`);
});

// Check if the file is readable and writable.
access(file, constants.R_OK | constants.W_OK, (err) => {
  console.log(`${file}${err ? 'is not' : 'is'} readable and writable`);
});

Do not use fs.access() to check for the accessibility of a file before calling fs.open(), fs.readFile(), or fs.writeFile(). 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.

write (NOT RECOMMENDED)

import { access, open, close } from 'node:fs';

access('myfile', (err) => {
  if (!err) {
    console.error('myfile already exists');
    return;
  }

  open('myfile', 'wx', (err, fd) => {
    if (err) throw err;

    try {
      writeMyData(fd);
    } finally {
      close(fd, (err) => {
        if (err) throw err;
      });
    }
  });
});

write (RECOMMENDED)

import { open, close } from 'node:fs';

open('myfile', 'wx', (err, fd) => {
  if (err) {
    if (err.code === 'EEXIST') {
      console.error('myfile already exists');
      return;
    }

    throw err;
  }

  try {
    writeMyData(fd);
  } finally {
    close(fd, (err) => {
      if (err) throw err;
    });
  }
});

read (NOT RECOMMENDED)

import { access, open, close } from 'node:fs';
access('myfile', (err) => {
  if (err) {
    if (err.code === 'ENOENT') {
      console.error('myfile does not exist');
      return;
    }

    throw err;
  }

  open('myfile', 'r', (err, fd) => {
    if (err) throw err;

    try {
      readMyData(fd);
    } finally {
      close(fd, (err) => {
        if (err) throw err;
      });
    }
  });
});

read (RECOMMENDED)

import { open, close } from 'node:fs';

open('myfile', 'r', (err, fd) => {
  if (err) {
    if (err.code === 'ENOENT') {
      console.error('myfile does not exist');
      return;
    }

    throw err;
  }

  try {
    readMyData(fd);
  } finally {
    close(fd, (err) => {
      if (err) throw err;
    });
  }
});

The "not recommended" examples above check for accessibility and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.

In general, check for the accessibility of a file only if the file will not be used directly, for example when its accessibility is a signal from another process.

On Windows, access-control policies (ACLs) on a directory may limit access to a file or directory. The fs.access() function, however, does not check the ACL and therefore may report that a path is accessible even if the ACL restricts the user from reading or writing to it.

Parameters

path: PathLike
mode: number | undefined = fs.constants.F_OK
optional
callback: NoParamCallback

Return Type

void

Overload 2

access(
path: PathLike,
callback: NoParamCallback,
): void

Asynchronously tests a user's permissions for the file specified by path.

Parameters

path: PathLike

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

callback: NoParamCallback

Return Type

void

function accessSync

Usage in Deno

import { accessSync } from "node:fs";
accessSync(
path: PathLike,
mode?: number,
): void

Synchronously 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_OK or 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 any of the accessibility checks fail, an Error will be thrown. Otherwise, the method will return undefined.

import { accessSync, constants } from 'node:fs';

try {
  accessSync('etc/passwd', constants.R_OK | constants.W_OK);
  console.log('can read/write');
} catch (err) {
  console.error('no access!');
}

Parameters

path: PathLike
mode: number = fs.constants.F_OK
optional

Return Type

void

function appendFile

Usage in Deno

import { appendFile } from "node:fs";

Overload 1

appendFile(
path: PathOrFileDescriptor,
data: string | Uint8Array,
options: WriteFileOptions,
callback: NoParamCallback,
): void

Asynchronously append data to a file, creating the file if it does not yet exist. data can be a string or a Buffer.

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

import { appendFile } from 'node:fs';

appendFile('message.txt', 'data to append', (err) => {
  if (err) throw err;
  console.log('The "data to append" was appended to file!');
});

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

import { appendFile } from 'node:fs';

appendFile('message.txt', 'data to append', 'utf8', callback);

The path may be specified as a numeric file descriptor that has been opened for appending (using fs.open() or fs.openSync()). The file descriptor will not be closed automatically.

import { open, close, appendFile } from 'node:fs';

function closeFd(fd) {
  close(fd, (err) => {
    if (err) throw err;
  });
}

open('message.txt', 'a', (err, fd) => {
  if (err) throw err;

  try {
    appendFile(fd, 'data to append', 'utf8', (err) => {
      closeFd(fd);
      if (err) throw err;
    });
  } catch (err) {
    closeFd(fd);
    throw err;
  }
});

Parameters

path: PathOrFileDescriptor

filename or file descriptor

data: string | Uint8Array
options: WriteFileOptions
callback: NoParamCallback

Return Type

void

Overload 2

appendFile(
file: PathOrFileDescriptor,
data: string | Uint8Array,
callback: NoParamCallback,
): void

Asynchronously append data to a file, creating the file if it does not exist.

Parameters

file: PathOrFileDescriptor

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

data: string | Uint8Array

The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.

callback: NoParamCallback

Return Type

void

function appendFileSync

Usage in Deno

import { appendFileSync } from "node:fs";
appendFileSync(
path: PathOrFileDescriptor,
data: string | Uint8Array,
options?: WriteFileOptions,
): void

Synchronously append data to a file, creating the file if it does not yet exist. data can be a string or a Buffer.

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

import { appendFileSync } from 'node:fs';

try {
  appendFileSync('message.txt', 'data to append');
  console.log('The "data to append" was appended to file!');
} catch (err) {
  // Handle the error
}

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

import { appendFileSync } from 'node:fs';

appendFileSync('message.txt', 'data to append', 'utf8');

The path may be specified as a numeric file descriptor that has been opened for appending (using fs.open() or fs.openSync()). The file descriptor will not be closed automatically.

import { openSync, closeSync, appendFileSync } from 'node:fs';

let fd;

try {
  fd = openSync('message.txt', 'a');
  appendFileSync(fd, 'data to append', 'utf8');
} catch (err) {
  // Handle the error
} finally {
  if (fd !== undefined)
    closeSync(fd);
}

Parameters

path: PathOrFileDescriptor

filename or file descriptor

data: string | Uint8Array
options: WriteFileOptions
optional

Return Type

void

function chmod

Usage in Deno

import { chmod } from "node:fs";
chmod(
path: PathLike,
mode: Mode,
callback: NoParamCallback,
): void

Asynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback.

See the POSIX chmod(2) documentation for more detail.

import { chmod } from 'node:fs';

chmod('my_file.txt', 0o775, (err) => {
  if (err) throw err;
  console.log('The permissions for file "my_file.txt" have been changed!');
});

Parameters

path: PathLike
mode: Mode
callback: NoParamCallback

Return Type

void

function chmodSync

Usage in Deno

import { chmodSync } from "node:fs";
chmodSync(
path: PathLike,
mode: Mode,
): void

For detailed information, see the documentation of the asynchronous version of this API: chmod.

See the POSIX chmod(2) documentation for more detail.

Parameters

path: PathLike
mode: Mode

Return Type

void

function chown

Usage in Deno

import { chown } from "node:fs";
chown(
path: PathLike,
uid: number,
gid: number,
callback: NoParamCallback,
): void

Asynchronously changes owner and group of a file. No arguments other than a possible exception are given to the completion callback.

See the POSIX chown(2) documentation for more detail.

Parameters

path: PathLike
uid: number
gid: number
callback: NoParamCallback

Return Type

void

function chownSync

Usage in Deno

import { chownSync } from "node:fs";
chownSync(
path: PathLike,
uid: number,
gid: number,
): void

Synchronously changes owner and group of a file. Returns undefined. This is the synchronous version of chown.

See the POSIX chown(2) documentation for more detail.

Parameters

path: PathLike
uid: number
gid: number

Return Type

void

function close

Usage in Deno

import { close } from "node:fs";
close(
fd: number,
callback?: NoParamCallback,
): void

Closes the file descriptor. No arguments other than a possible exception are given to the completion callback.

Calling fs.close() on any file descriptor (fd) that is currently in use through any other fs operation may lead to undefined behavior.

See the POSIX close(2) documentation for more detail.

Parameters

fd: number
callback: NoParamCallback
optional

Return Type

void

function closeSync

Usage in Deno

import { closeSync } from "node:fs";
closeSync(fd: number): void

Closes the file descriptor. Returns undefined.

Calling fs.closeSync() on any file descriptor (fd) that is currently in use through any other fs operation may lead to undefined behavior.

See the POSIX close(2) documentation for more detail.

Parameters

fd: number

Return Type

void

function copyFile

Usage in Deno

import { copyFile } from "node:fs";

Overload 1

copyFile(
src: PathLike,
dest: PathLike,
callback: NoParamCallback,
): void

Asynchronously copies src to dest. By default, dest is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.

mode is an optional integer that specifies 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).

  • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already exists.
  • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.
  • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFile, constants } from 'node:fs';

function callback(err) {
  if (err) throw err;
  console.log('source.txt was copied to destination.txt');
}

// destination.txt will be created or overwritten by default.
copyFile('source.txt', 'destination.txt', callback);

// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);

Parameters

src: PathLike

source filename to copy

dest: PathLike

destination filename of the copy operation

callback: NoParamCallback

Return Type

void

Overload 2

copyFile(
src: PathLike,
dest: PathLike,
mode: number,
callback: NoParamCallback,
): void

Parameters

src: PathLike
dest: PathLike
mode: number
callback: NoParamCallback

Return Type

void

function copyFileSync

Usage in Deno

import { copyFileSync } from "node:fs";
copyFileSync(
src: PathLike,
dest: PathLike,
mode?: number,
): void

Synchronously copies src to dest. By default, dest is overwritten if it already exists. Returns undefined. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.

mode is an optional integer that specifies 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).

  • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already exists.
  • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.
  • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFileSync, constants } from 'node:fs';

// destination.txt will be created or overwritten by default.
copyFileSync('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');

// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);

Parameters

src: PathLike

source filename to copy

dest: PathLike

destination filename of the copy operation

mode: number = 0
optional

modifiers for copy operation.

Return Type

void

function cp

unstable

Usage in Deno

import { cp } from "node:fs";

Overload 1

cp(
source: string | URL,
destination: string | URL,
callback: (err: ErrnoException | null) => void,
): void

Asynchronously copies the entire directory structure from src to dest, including subdirectories and files.

When copying a directory to another directory, globs are not supported and behavior is similar to cp dir1/ dir2/.

Parameters

source: string | URL
destination: string | URL
callback: (err: ErrnoException | null) => void

Return Type

void

Overload 2

cp(
source: string | URL,
destination: string | URL,
opts: CopyOptions,
callback: (err: ErrnoException | null) => void,
): void

Parameters

source: string | URL
destination: string | URL
opts: CopyOptions
callback: (err: ErrnoException | null) => void

Return Type

void

function cpSync

unstable

Usage in Deno

import { cpSync } from "node:fs";
cpSync(
source: string | URL,
destination: string | URL,
opts?: CopySyncOptions,
): void

Synchronously copies the entire directory structure from src to dest, including subdirectories and files.

When copying a directory to another directory, globs are not supported and behavior is similar to cp dir1/ dir2/.

Parameters

source: string | URL
destination: string | URL
opts: CopySyncOptions
optional

Return Type

void

function createReadStream

Usage in Deno

import { createReadStream } from "node:fs";
createReadStream(
path: PathLike,
options?: BufferEncoding | ReadStreamOptions,
): ReadStream

options can include start and end values to read a range of bytes from the file instead of the entire file. Both start and end are inclusive and start counting at 0, allowed values are in the [0, Number.MAX_SAFE_INTEGER] range. If fd is specified and start is omitted or undefined, fs.createReadStream() reads sequentially from the current file position. The encoding can be any one of those accepted by Buffer.

If fd is specified, ReadStream will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds should be passed to net.Socket.

If fd points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally.

By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.

By providing the fs option, it is possible to override the corresponding fs implementations for open, read, and close. When providing the fs option, an override for read is required. If no fd is provided, an override for open is also required. If autoClose is true, an override for close is also required.

import { createReadStream } from 'node:fs';

// Create a stream from some character device.
const stream = createReadStream('/dev/input/event0');
setTimeout(() => {
  stream.close(); // This may not close the stream.
  // Artificially marking end-of-stream, as if the underlying resource had
  // indicated end-of-file by itself, allows the stream to close.
  // This does not cancel pending read operations, and if there is such an
  // operation, the process may still not be able to exit successfully
  // until it finishes.
  stream.push(null);
  stream.read(0);
}, 100);

If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. If autoClose is set to true (default behavior), on 'error' or 'end' the file descriptor will be closed automatically.

mode sets the file mode (permission and sticky bits), but only if the file was created.

An example to read the last 10 bytes of a file which is 100 bytes long:

import { createReadStream } from 'node:fs';

createReadStream('sample.txt', { start: 90, end: 99 });

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

Parameters

path: PathLike
options: BufferEncoding | ReadStreamOptions
optional

Return Type

ReadStream

function createWriteStream

Usage in Deno

import { createWriteStream } from "node:fs";
createWriteStream(
path: PathLike,
options?: BufferEncoding | WriteStreamOptions,
): WriteStream

options may also include a start option to allow writing data at some position past the beginning of the file, allowed values are in the [0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather than replacing it may require the flags option to be set to r+ rather than the default w. The encoding can be any one of those accepted by Buffer.

If autoClose is set to true (default behavior) on 'error' or 'finish' the file descriptor will be closed automatically. If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.

By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.

By providing the fs option it is possible to override the corresponding fs implementations for open, write, writev, and close. Overriding write() without writev() can reduce performance as some optimizations (_writev()) will be disabled. When providing the fs option, overrides for at least one of write and writev are required. If no fd option is supplied, an override for open is also required. If autoClose is true, an override for close is also required.

Like fs.ReadStream, if fd is specified, fs.WriteStream will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds should be passed to net.Socket.

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

Parameters

path: PathLike
options: BufferEncoding | WriteStreamOptions
optional

Return Type

WriteStream

function existsSync

Usage in Deno

import { existsSync } from "node:fs";
existsSync(path: PathLike): boolean

Returns true if the path exists, false otherwise.

For detailed information, see the documentation of the asynchronous version of this API: exists.

fs.exists() is deprecated, but fs.existsSync() is not. The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.

import { existsSync } from 'node:fs';

if (existsSync('/etc/passwd'))
  console.log('The path exists.');

Parameters

path: PathLike

Return Type

boolean

function fchmod

Usage in Deno

import { fchmod } from "node:fs";
fchmod(
fd: number,
mode: Mode,
callback: NoParamCallback,
): void

Sets the permissions on the file. No arguments other than a possible exception are given to the completion callback.

See the POSIX fchmod(2) documentation for more detail.

Parameters

fd: number
mode: Mode
callback: NoParamCallback

Return Type

void

function fchmodSync

Usage in Deno

import { fchmodSync } from "node:fs";
fchmodSync(
fd: number,
mode: Mode,
): void

Sets the permissions on the file. Returns undefined.

See the POSIX fchmod(2) documentation for more detail.

Parameters

fd: number
mode: Mode

Return Type

void

function fchown

Usage in Deno

import { fchown } from "node:fs";
fchown(
fd: number,
uid: number,
gid: number,
callback: NoParamCallback,
): void

Sets the owner of the file. No arguments other than a possible exception are given to the completion callback.

See the POSIX fchown(2) documentation for more detail.

Parameters

fd: number
uid: number
gid: number
callback: NoParamCallback

Return Type

void

function fchownSync

Usage in Deno

import { fchownSync } from "node:fs";
fchownSync(
fd: number,
uid: number,
gid: number,
): void

Sets the owner of the file. Returns undefined.

See the POSIX fchown(2) documentation for more detail.

Parameters

fd: number
uid: number

The file's new owner's user id.

gid: number

The file's new group's group id.

Return Type

void

function fdatasync

Usage in Deno

import { fdatasync } from "node:fs";
fdatasync(
fd: number,
callback: NoParamCallback,
): void

Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. No arguments other than a possible exception are given to the completion callback.

Parameters

fd: number
callback: NoParamCallback

Return Type

void

function fdatasyncSync

Usage in Deno

import { fdatasyncSync } from "node:fs";
fdatasyncSync(fd: number): void

Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. Returns undefined.

Parameters

fd: number

Return Type

void

function fstat

Usage in Deno

import { fstat } from "node:fs";

Overload 1

fstat(
fd: number,
callback: (
err: ErrnoException | null,
stats: Stats,
) => void
,
): void

Invokes the callback with the fs.Stats for the file descriptor.

See the POSIX fstat(2) documentation for more detail.

Parameters

fd: number
callback: (
err: ErrnoException | null,
stats: Stats,
) => void

Return Type

void

Overload 2

fstat(
fd: number,
options: (StatOptions & { bigint?: false | undefined; }) | undefined,
callback: (
err: ErrnoException | null,
stats: Stats,
) => void
,
): void

Parameters

fd: number
options: (StatOptions & { bigint?: false | undefined; }) | undefined
callback: (
err: ErrnoException | null,
stats: Stats,
) => void

Return Type

void

Overload 3

fstat(
fd: number,
options: StatOptions & { bigint: true; },
callback: (
err: ErrnoException | null,
stats: BigIntStats,
) => void
,
): void

Parameters

fd: number
options: StatOptions & { bigint: true; }
callback: (
err: ErrnoException | null,
stats: BigIntStats,
) => void

Return Type

void

Overload 4

fstat(
fd: number,
options: StatOptions | undefined,
callback: (
err: ErrnoException | null,
stats: Stats | BigIntStats,
) => void
,
): void

Parameters

fd: number
options: StatOptions | undefined
callback: (
err: ErrnoException | null,
stats: Stats | BigIntStats,
) => void

Return Type

void

function fstatSync

Usage in Deno

import { fstatSync } from "node:fs";

Overload 1

fstatSync(
fd: number,
options?: StatOptions & { bigint?: false | undefined; },
): Stats

Retrieves the fs.Stats for the file descriptor.

See the POSIX fstat(2) documentation for more detail.

Parameters

fd: number
options: StatOptions & { bigint?: false | undefined; }
optional

Return Type

Stats

Overload 2

fstatSync(
fd: number,
options: StatOptions & { bigint: true; },
): BigIntStats

Parameters

fd: number
options: StatOptions & { bigint: true; }

Return Type

BigIntStats

Overload 3

fstatSync(
fd: number,
options?: StatOptions,
): Stats | BigIntStats

Parameters

fd: number
options: StatOptions
optional

Return Type

Stats | BigIntStats

function fsync

Usage in Deno

import { fsync } from "node:fs";
fsync(
fd: number,
callback: NoParamCallback,
): void

Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. No arguments other than a possible exception are given to the completion callback.

Parameters

fd: number
callback: NoParamCallback

Return Type

void

function fsyncSync

Usage in Deno

import { fsyncSync } from "node:fs";
fsyncSync(fd: number): void

Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. Returns undefined.

Parameters

fd: number

Return Type

void

function ftruncate

Usage in Deno

import { ftruncate } from "node:fs";

Overload 1

ftruncate(
fd: number,
len: number | undefined,
callback: NoParamCallback,
): void

Truncates the file descriptor. No arguments other than a possible exception are given to the completion callback.

See the POSIX ftruncate(2) documentation for more detail.

If the file referred to by the file descriptor was larger than len bytes, only the first len bytes will be retained in the file.

For example, the following program retains only the first four bytes of the file:

import { open, close, ftruncate } from 'node:fs';

function closeFd(fd) {
  close(fd, (err) => {
    if (err) throw err;
  });
}

open('temp.txt', 'r+', (err, fd) => {
  if (err) throw err;

  try {
    ftruncate(fd, 4, (err) => {
      closeFd(fd);
      if (err) throw err;
    });
  } catch (err) {
    closeFd(fd);
    if (err) throw err;
  }
});

If the file previously was shorter than len bytes, it is extended, and the extended part is filled with null bytes ('\0'):

If len is negative then 0 will be used.

Parameters

fd: number
len: number | undefined = 0
optional
callback: NoParamCallback

Return Type

void

Overload 2

ftruncate(
fd: number,
callback: NoParamCallback,
): void

Asynchronous ftruncate(2) - Truncate a file to a specified length.

Parameters

fd: number

A file descriptor.

callback: NoParamCallback

Return Type

void

function ftruncateSync

Usage in Deno

import { ftruncateSync } from "node:fs";
ftruncateSync(
fd: number,
len?: number,
): void

Truncates the file descriptor. Returns undefined.

For detailed information, see the documentation of the asynchronous version of this API: ftruncate.

Parameters

fd: number
len: number = 0
optional

Return Type

void

function futimes

Usage in Deno

import { futimes } from "node:fs";
futimes(
fd: number,
atime: TimeLike,
mtime: TimeLike,
callback: NoParamCallback,
): void

Change the file system timestamps of the object referenced by the supplied file descriptor. See utimes.

Parameters

fd: number
atime: TimeLike
mtime: TimeLike
callback: NoParamCallback

Return Type

void

function futimesSync

Usage in Deno

import { futimesSync } from "node:fs";
futimesSync(
fd: number,
atime: TimeLike,
mtime: TimeLike,
): void

Synchronous version of futimes. Returns undefined.

Parameters

fd: number
atime: TimeLike
mtime: TimeLike

Return Type

void

function glob

Usage in Deno

import { glob } from "node:fs";

Overload 1

glob(
pattern: string | string[],
callback: (
err: ErrnoException | null,
matches: string[],
) => void
,
): void

Retrieves the files matching the specified pattern.

Parameters

pattern: string | string[]
callback: (
err: ErrnoException | null,
matches: string[],
) => void

Return Type

void

Overload 2

glob(
pattern: string | string[],
options: GlobOptionsWithFileTypes,
callback: (
err: ErrnoException | null,
matches: Dirent[],
) => void
,
): void

Parameters

pattern: string | string[]
options: GlobOptionsWithFileTypes
callback: (
err: ErrnoException | null,
matches: Dirent[],
) => void

Return Type

void

Overload 3

glob(
pattern: string | string[],
options: GlobOptionsWithoutFileTypes,
callback: (
err: ErrnoException | null,
matches: string[],
) => void
,
): void

Parameters

pattern: string | string[]
options: GlobOptionsWithoutFileTypes
callback: (
err: ErrnoException | null,
matches: string[],
) => void

Return Type

void

Overload 4

glob(
pattern: string | string[],
options: GlobOptions,
callback: (
err: ErrnoException | null,
matches: Dirent[] | string[],
) => void
,
): void

Parameters

pattern: string | string[]
options: GlobOptions
callback: (
err: ErrnoException | null,
matches: Dirent[] | string[],
) => void

Return Type

void

function globSync

Usage in Deno

import { globSync } from "node:fs";

Overload 1

globSync(pattern: string | string[]): string[]

Retrieves the files matching the specified pattern.

Parameters

pattern: string | string[]

Return Type

string[]

Overload 2

globSync(
pattern: string | string[],
options: GlobOptionsWithFileTypes,
): Dirent[]

Parameters

pattern: string | string[]
options: GlobOptionsWithFileTypes

Return Type

Dirent[]

Overload 3

globSync(
pattern: string | string[],
options: GlobOptionsWithoutFileTypes,
): string[]

Parameters

pattern: string | string[]
options: GlobOptionsWithoutFileTypes

Return Type

string[]

Overload 4

globSync(
pattern: string | string[],
options: GlobOptions,
): Dirent[] | string[]

Parameters

pattern: string | string[]
options: GlobOptions

Return Type

Dirent[] | string[]

function lchown

Usage in Deno

import { lchown } from "node:fs";
lchown(
path: PathLike,
uid: number,
gid: number,
callback: NoParamCallback,
): void

Set the owner of the symbolic link. No arguments other than a possible exception are given to the completion callback.

See the POSIX lchown(2) documentation for more detail.

Parameters

path: PathLike
uid: number
gid: number
callback: NoParamCallback

Return Type

void

function lchownSync

Usage in Deno

import { lchownSync } from "node:fs";
lchownSync(
path: PathLike,
uid: number,
gid: number,
): void

Set the owner for the path. Returns undefined.

See the POSIX lchown(2) documentation for more details.

Parameters

path: PathLike
uid: number

The file's new owner's user id.

gid: number

The file's new group's group id.

Return Type

void

function link

Usage in Deno

import { link } from "node:fs";
link(
existingPath: PathLike,
newPath: PathLike,
callback: NoParamCallback,
): void

Creates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail. No arguments other than a possible exception are given to the completion callback.

Parameters

existingPath: PathLike
newPath: PathLike
callback: NoParamCallback

Return Type

void

function linkSync

Usage in Deno

import { linkSync } from "node:fs";
linkSync(
existingPath: PathLike,
newPath: PathLike,
): void

Creates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail. Returns undefined.

Parameters

existingPath: PathLike
newPath: PathLike

Return Type

void

function lstat

Usage in Deno

import { lstat } from "node:fs";

Overload 1

lstat(
path: PathLike,
callback: (
err: ErrnoException | null,
stats: Stats,
) => void
,
): void

Retrieves the fs.Stats for the symbolic link referred to by the path. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.

See the POSIX lstat(2) documentation for more details.

Parameters

path: PathLike
callback: (
err: ErrnoException | null,
stats: Stats,
) => void

Return Type

void

Overload 2

lstat(
path: PathLike,
options: (StatOptions & { bigint?: false | undefined; }) | undefined,
callback: (
err: ErrnoException | null,
stats: Stats,
) => void
,
): void

Parameters

path: PathLike
options: (StatOptions & { bigint?: false | undefined; }) | undefined
callback: (
err: ErrnoException | null,
stats: Stats,
) => void

Return Type

void

Overload 3

lstat(
path: PathLike,
options: StatOptions & { bigint: true; },
callback: (
err: ErrnoException | null,
stats: BigIntStats,
) => void
,
): void

Parameters

path: PathLike
options: StatOptions & { bigint: true; }
callback: (
err: ErrnoException | null,
stats: BigIntStats,
) => void

Return Type

void

Overload 4

lstat(
path: PathLike,
options: StatOptions | undefined,
callback: (
err: ErrnoException | null,
stats: Stats | BigIntStats,
) => void
,
): void

Parameters

path: PathLike
options: StatOptions | undefined
callback: (
err: ErrnoException | null,
stats: Stats | BigIntStats,
) => void

Return Type

void

function lutimes

Usage in Deno

import { lutimes } from "node:fs";
lutimes(
path: PathLike,
atime: TimeLike,
mtime: TimeLike,
callback: NoParamCallback,
): void

Changes the access and modification times of a file in the same way as utimes, with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed.

No arguments other than a possible exception are given to the completion callback.

Parameters

path: PathLike
atime: TimeLike
mtime: TimeLike
callback: NoParamCallback

Return Type

void

function lutimesSync

Usage in Deno

import { lutimesSync } from "node:fs";
lutimesSync(
path: PathLike,
atime: TimeLike,
mtime: TimeLike,
): void

Change the file system timestamps of the symbolic link referenced by path. Returns undefined, or throws an exception when parameters are incorrect or the operation fails. This is the synchronous version of lutimes.

Parameters

path: PathLike
atime: TimeLike
mtime: TimeLike

Return Type

void

function mkdir

Usage in Deno

import { mkdir } from "node:fs";

Overload 1

mkdir(
path: PathLike,
options: MakeDirectoryOptions & { recursive: true; },
callback: (
err: ErrnoException | null,
path?: string,
) => void
,
): void

Asynchronously creates a directory.

The callback is given a possible exception and, if recursive is true, the first directory path created, (err[, path]).path can still be undefined when recursive is true, if no directory was created (for instance, if it was previously created).

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

import { mkdir } from 'node:fs';

// Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist.
mkdir('./tmp/a/apple', { recursive: true }, (err) => {
  if (err) throw err;
});

On Windows, using fs.mkdir() on the root directory even with recursion will result in an error:

import { mkdir } from 'node:fs';

mkdir('/', { recursive: true }, (err) => {
  // => [Error: EPERM: operation not permitted, mkdir 'C:\']
});

See the POSIX mkdir(2) documentation for more details.

Parameters

path: PathLike
options: MakeDirectoryOptions & { recursive: true; }
callback: (
err: ErrnoException | null,
path?: string,
) => void

Return Type

void

Overload 2

mkdir(
path: PathLike,
options:
Mode
| (MakeDirectoryOptions & { recursive?: false | undefined; })
| null
| undefined
,
callback: NoParamCallback,
): 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.

options:
Mode
| (MakeDirectoryOptions & { recursive?: false | undefined; })
| null
| undefined

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.

callback: NoParamCallback

Return Type

void

Overload 3

mkdir(
path: PathLike,
options:
Mode
| MakeDirectoryOptions
| null
| undefined
,
callback: (
err: ErrnoException | null,
path?: string,
) => void
,
): 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.

options:
Mode
| MakeDirectoryOptions
| null
| undefined

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.

callback: (
err: ErrnoException | null,
path?: string,
) => void

Return Type

void

Overload 4

mkdir(
path: PathLike,
callback: NoParamCallback,
): void

Asynchronous mkdir(2) - create a directory with a mode of 0o777.

Parameters

path: PathLike

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

callback: NoParamCallback

Return Type

void

function mkdirSync

Usage in Deno

import { mkdirSync } from "node:fs";

Overload 1

mkdirSync(
path: PathLike,
options: MakeDirectoryOptions & { recursive: true; },
): string | undefined

Synchronously creates a directory. Returns undefined, or if recursive is true, the first directory path created. This is the synchronous version of mkdir.

See the POSIX mkdir(2) documentation for more details.

Parameters

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

Return Type

string | undefined

Overload 2

mkdirSync(
path: PathLike,
options?:
Mode
| (MakeDirectoryOptions & { recursive?: false | undefined; })
| null
,
): void

Synchronous mkdir(2) - create a directory.

Parameters

path: PathLike

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

options:
Mode
| (MakeDirectoryOptions & { recursive?: false | undefined; })
| null
optional

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.

Return Type

void

Overload 3

mkdirSync(
path: PathLike,
options?:
Mode
| MakeDirectoryOptions
| null
,
): string | undefined

Synchronous mkdir(2) - create a directory.

Parameters

path: PathLike

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

options:
Mode
| MakeDirectoryOptions
| null
optional

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.

Return Type

string | undefined

function mkdtemp

Usage in Deno

import { mkdtemp } from "node:fs";

Overload 1

mkdtemp(
prefix: string,
options: EncodingOption,
callback: (
err: ErrnoException | null,
folder: string,
) => void
,
): void

Creates a unique temporary directory.

Generates six random characters to be appended behind a required prefix to create a unique temporary directory. 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 created directory path is passed as a string to the callback's second parameter.

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';
import { join } from 'node:path';
import { tmpdir } from 'node:os';

mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {
  if (err) throw err;
  console.log(directory);
  // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
});

The fs.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, the prefixmust end with a trailing platform-specific path separator (import { sep } from 'node:path').

import { tmpdir } from 'node:os';
import { mkdtemp } from 'node:fs';

// The parent directory for the new temporary directory
const tmpDir = tmpdir();

// This method is *INCORRECT*:
mkdtemp(tmpDir, (err, directory) => {
  if (err) throw err;
  console.log(directory);
  // Will print something similar to `/tmpabc123`.
  // A new temporary directory is created at the file system root
  // rather than *within* the /tmp directory.
});

// This method is *CORRECT*:
import { sep } from 'node:path';
mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
  if (err) throw err;
  console.log(directory);
  // Will print something similar to `/tmp/abc123`.
  // A new temporary directory is created within
  // the /tmp directory.
});

Parameters

prefix: string
options: EncodingOption
callback: (
err: ErrnoException | null,
folder: string,
) => void

Return Type

void

Overload 2

mkdtemp(
prefix: string,
options: "buffer" | { encoding: "buffer"; },
callback: (
err: ErrnoException | null,
folder: Buffer,
) => void
,
): void

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: "buffer" | { encoding: "buffer"; }

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

callback: (
err: ErrnoException | null,
folder: Buffer,
) => void

Return Type

void

Overload 3

mkdtemp(
prefix: string,
options: EncodingOption,
callback: (
err: ErrnoException | null,
folder: string | Buffer,
) => void
,
): void

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: EncodingOption

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

callback: (
err: ErrnoException | null,
folder: string | Buffer,
) => void

Return Type

void

Overload 4

mkdtemp(
prefix: string,
callback: (
err: ErrnoException | null,
folder: string,
) => void
,
): void

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
callback: (
err: ErrnoException | null,
folder: string,
) => void

Return Type

void

function mkdtempSync

Usage in Deno

import { mkdtempSync } from "node:fs";

Overload 1

mkdtempSync(
prefix: string,
options?: EncodingOption,
): string

Returns the created directory path.

For detailed information, see the documentation of the asynchronous version of this API: mkdtemp.

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

Parameters

prefix: string
options: EncodingOption
optional

Return Type

string

Overload 2

mkdtempSync(
prefix: string,
options: BufferEncodingOption,
): Buffer

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

Return Type

Buffer

Overload 3

mkdtempSync(
prefix: string,
options?: EncodingOption,
): string | Buffer

Synchronously 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: EncodingOption
optional

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

Return Type

string | Buffer

function open

Usage in Deno

import { open } from "node:fs";

Overload 1

open(
path: PathLike,
flags: OpenMode | undefined,
mode:
Mode
| undefined
| null
,
callback: (
err: ErrnoException | null,
fd: number,
) => void
,
): void

Asynchronous file open. See the POSIX open(2) documentation for more details.

mode sets the file mode (permission and sticky bits), but only if the file was created. On Windows, only the write permission can be manipulated; see chmod.

The callback gets two arguments (err, fd).

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.

Functions based on fs.open() exhibit this behavior as well:fs.writeFile(), fs.readFile(), etc.

Parameters

path: PathLike
flags: OpenMode | undefined = 'r'
optional

See support of file system flags``.

mode:
Mode
| undefined
| null
= 0o666
optional
callback: (
err: ErrnoException | null,
fd: number,
) => void

Return Type

void

Overload 2

open(
path: PathLike,
flags: OpenMode | undefined,
callback: (
err: ErrnoException | null,
fd: number,
) => void
,
): void

Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be 0o666.

Parameters

path: PathLike

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

flags: OpenMode | undefined = 'r'
optional

See support of file system flags``.

callback: (
err: ErrnoException | null,
fd: number,
) => void

Return Type

void

Overload 3

open(
path: PathLike,
callback: (
err: ErrnoException | null,
fd: number,
) => void
,
): void

Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be 0o666.

Parameters

path: PathLike

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

callback: (
err: ErrnoException | null,
fd: number,
) => void

Return Type

void

function openAsBlob

unstable

Usage in Deno

import { openAsBlob } from "node:fs";
openAsBlob(
path: PathLike,
options?: OpenAsBlobOptions,
): Promise<Blob>

Returns a Blob whose data is backed by the given file.

The file must not be modified after the Blob is created. Any modifications will cause reading the Blob data to fail with a DOMException error. Synchronous stat operations on the file when the Blob is created, and before each read in order to detect whether the file data has been modified on disk.

import { openAsBlob } from 'node:fs';

const blob = await openAsBlob('the.file.txt');
const ab = await blob.arrayBuffer();
blob.stream();

Parameters

path: PathLike
options: OpenAsBlobOptions
optional

Return Type

Promise<Blob>

function opendir

Usage in Deno

import { opendir } from "node:fs";

Overload 1

opendir(
path: PathLike,
cb: (
err: ErrnoException | null,
dir: Dir,
) => void
,
): void

Asynchronously open a directory. See the POSIX opendir(3) documentation for more details.

Creates an fs.Dir, which contains all further functions for reading from and cleaning up the directory.

The encoding option sets the encoding for the path while opening the directory and subsequent read operations.

Parameters

path: PathLike
cb: (
err: ErrnoException | null,
dir: Dir,
) => void

Return Type

void

Overload 2

opendir(
path: PathLike,
options: OpenDirOptions,
cb: (
err: ErrnoException | null,
dir: Dir,
) => void
,
): void

Parameters

path: PathLike
options: OpenDirOptions
cb: (
err: ErrnoException | null,
dir: Dir,
) => void

Return Type

void

function opendirSync

Usage in Deno

import { opendirSync } from "node:fs";
opendirSync(
path: PathLike,
options?: OpenDirOptions,
): Dir

Synchronously open a directory. See opendir(3).

Creates an fs.Dir, which contains all further functions for reading from and cleaning up the directory.

The encoding option sets the encoding for the path while opening the directory and subsequent read operations.

Parameters

path: PathLike
options: OpenDirOptions
optional

Return Type

Dir

function openSync

Usage in Deno

import { openSync } from "node:fs";
openSync(
path: PathLike,
flags: OpenMode,
mode?: Mode | null,
): number

Returns an integer representing the file descriptor.

For detailed information, see the documentation of the asynchronous version of this API: open.

Parameters

path: PathLike
flags: OpenMode = 'r'
optional
mode: Mode | null = 0o666
optional

Return Type

number

function promises.access

Usage in Deno

import { promises } from "node:fs";
const { access } = promises;
access(
path: PathLike,
mode?: number,
): 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_OK or 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 fulfilled 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
mode: number = fs.constants.F_OK
optional

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.appendFile

Usage in Deno

import { promises } from "node:fs";
const { appendFile } = promises;
appendFile(
path: PathLike | FileHandle,
data: string | Uint8Array,
options?:
(
ObjectEncodingOptions
& FlagAndOpenMode
& { flush?: boolean | undefined; }
)

| BufferEncoding
| null
,
): Promise<void>

Asynchronously append data to a file, creating the file if it does not yet exist. data can be a string or 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.

The path may be specified as a FileHandle that has been opened for appending (using fsPromises.open()).

Parameters

path: PathLike | FileHandle

filename or {FileHandle}

data: string | Uint8Array
options:
(
ObjectEncodingOptions
& FlagAndOpenMode
& { flush?: boolean | undefined; }
)

| BufferEncoding
| null
optional

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.chmod

Usage in Deno

import { promises } from "node:fs";
const { chmod } = promises;
chmod(
path: PathLike,
mode: Mode,
): Promise<void>

Changes the permissions of a file.

Parameters

path: PathLike
mode: Mode

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.chown

Usage in Deno

import { promises } from "node:fs";
const { chown } = promises;
chown(
path: PathLike,
uid: number,
gid: number,
): Promise<void>

Changes the ownership of a file.

Parameters

path: PathLike
uid: number
gid: number

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.copyFile

Usage in Deno

import { promises } from "node:fs";
const { copyFile } = promises;
copyFile(
src: PathLike,
dest: PathLike,
mode?: number,
): 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

mode: number = 0
optional

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)

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.cp

unstable

Usage in Deno

import { promises } from "node:fs";
const { cp } = promises;
cp(
source: string | URL,
destination: string | URL,
opts?: CopyOptions,
): Promise<void>

Asynchronously copies the entire directory structure from src to dest, including subdirectories and files.

When copying a directory to another directory, globs are not supported and behavior is similar to cp dir1/ dir2/.

Parameters

source: string | URL
destination: string | URL
opts: CopyOptions
optional

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.glob

Usage in Deno

import { promises } from "node:fs";
const { glob } = promises;

Overload 1

glob(pattern: string | string[]): AsyncIterator<string>

Retrieves the files matching the specified pattern.

Parameters

pattern: string | string[]

Return Type

AsyncIterator<string>

Overload 2

glob(
pattern: string | string[],
opt: GlobOptionsWithFileTypes,
): AsyncIterator<Dirent>

Parameters

pattern: string | string[]
opt: GlobOptionsWithFileTypes

Return Type

AsyncIterator<Dirent>

Overload 3

glob(
pattern: string | string[],
opt: GlobOptionsWithoutFileTypes,
): AsyncIterator<string>

Parameters

pattern: string | string[]
opt: GlobOptionsWithoutFileTypes

Return Type

AsyncIterator<string>

Overload 4

glob(
pattern: string | string[],
opt: GlobOptions,
): AsyncIterator<Dirent | string>

Parameters

pattern: string | string[]
opt: GlobOptions

Return Type

AsyncIterator<Dirent | string>

function promises.lchown

Usage in Deno

import { promises } from "node:fs";
const { lchown } = promises;
lchown(
path: PathLike,
uid: number,
gid: number,
): Promise<void>

Changes the ownership on a symbolic link.

Parameters

path: PathLike
uid: number
gid: number

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.link

Usage in Deno

import { promises } from "node:fs";
const { link } = promises;
link(
existingPath: PathLike,
newPath: PathLike,
): Promise<void>

Creates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail.

Parameters

existingPath: PathLike
newPath: PathLike

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.lstat

Usage in Deno

import { promises } from "node:fs";
const { lstat } = promises;

Overload 1

lstat(
path: PathLike,
opts?: StatOptions & { bigint?: false | undefined; },
): Promise<Stats>

Equivalent to fsPromises.stat() unless path refers to a symbolic link, in which case the link itself is stat-ed, not the file that it refers to. Refer to the POSIX lstat(2) document for more detail.

Parameters

path: PathLike
opts: StatOptions & { bigint?: false | undefined; }
optional

Return Type

Promise<Stats>

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

Overload 2

lstat(
path: PathLike,
opts: StatOptions & { bigint: true; },
): Promise<BigIntStats>

Parameters

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

Return Type

Promise<BigIntStats>

Overload 3

lstat(
path: PathLike,
opts?: StatOptions,
): Promise<Stats | BigIntStats>

Parameters

path: PathLike
opts: StatOptions
optional

Return Type

Promise<Stats | BigIntStats>

function promises.lutimes

Usage in Deno

import { promises } from "node:fs";
const { lutimes } = promises;
lutimes(
path: PathLike,
atime: TimeLike,
mtime: TimeLike,
): Promise<void>

Changes the access and modification times of a file in the same way as fsPromises.utimes(), with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed.

Parameters

path: PathLike
atime: TimeLike
mtime: TimeLike

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.mkdir

Usage in Deno

import { promises } from "node:fs";
const { mkdir } = promises;

Overload 1

mkdir(
path: PathLike,
options: MakeDirectoryOptions & { recursive: true; },
): 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 recursive property indicating whether parent directories should be created. Calling fsPromises.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; }

Return Type

Promise<string | undefined>

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

Overload 2

mkdir(
path: PathLike,
options?:
Mode
| (MakeDirectoryOptions & { recursive?: false | undefined; })
| null
,
): 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.

options:
Mode
| (MakeDirectoryOptions & { recursive?: false | undefined; })
| null
optional

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.

Return Type

Promise<void>

Overload 3

mkdir(
path: PathLike,
options?:
Mode
| MakeDirectoryOptions
| null
,
): 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.

options:
Mode
| MakeDirectoryOptions
| null
optional

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.

Return Type

Promise<string | undefined>

function promises.mkdtemp

Usage in Deno

import { promises } from "node:fs";
const { mkdtemp } = promises;

Overload 1

mkdtemp(
prefix: string,
options?:
ObjectEncodingOptions
| BufferEncoding
| null
,
): 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, the prefix must end with a trailing platform-specific path separator (import { sep } from 'node:path').

Parameters

prefix: string
options:
ObjectEncodingOptions
| BufferEncoding
| null
optional

Return Type

Promise<string>

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

Overload 2

mkdtemp(
prefix: string,
options: BufferEncodingOption,
): 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.

Return Type

Promise<Buffer>

Overload 3

mkdtemp(
prefix: string,
options?:
ObjectEncodingOptions
| BufferEncoding
| null
,
): 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
options:
ObjectEncodingOptions
| BufferEncoding
| null
optional

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

Return Type

Promise<string | Buffer>

function promises.open

Usage in Deno

import { promises } from "node:fs";
const { open } = promises;
open(
path: PathLike,
flags?: string | number,
mode?: 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
flags: string | number = 'r'
optional

See support of file system flags``.

mode: Mode = 0o666
optional

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

Return Type

Promise<FileHandle>

Fulfills with a {FileHandle} object.


function promises.opendir

Usage in Deno

import { promises } from "node:fs";
const { opendir } = promises;
opendir(
path: PathLike,
options?: OpenDirOptions,
): Promise<Dir>

Asynchronously open a directory for iterative scanning. See the POSIX opendir(3) documentation for more detail.

Creates an fs.Dir, which contains all further functions for reading from and cleaning up the directory.

The encoding option sets the encoding for the path while opening the directory and subsequent read operations.

Example using async iteration:

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

try {
  const dir = await opendir('./');
  for await (const dirent of dir)
    console.log(dirent.name);
} catch (err) {
  console.error(err);
}

When using the async iterator, the fs.Dir object will be automatically closed after the iterator exits.

Parameters

path: PathLike
options: OpenDirOptions
optional

Return Type

Promise<Dir>

Fulfills with an {fs.Dir}.


function promises.readdir

Usage in Deno

import { promises } from "node:fs";
const { readdir } = promises;

Overload 1

readdir(
path: PathLike,
options?:
(ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| null
,
): 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 returned 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
options:
(ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| null
optional

Return Type

Promise<string[]>

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

Overload 2

readdir(
path: PathLike,
options: { encoding: "buffer"; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | "buffer",
): 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: { encoding: "buffer"; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | "buffer"

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

Return Type

Promise<Buffer[]>

Overload 3

readdir(
path: PathLike,
options?:
(ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| null
,
): 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.

options:
(ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| null
optional

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

Return Type

Promise<string[] | Buffer[]>

Overload 4

readdir(
path: PathLike,
options: ObjectEncodingOptions & { withFileTypes: true; recursive?: boolean | undefined; },
): 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 & { withFileTypes: true; recursive?: boolean | undefined; }

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

Return Type

Promise<Dirent[]>

function promises.readFile

Usage in Deno

import { promises } from "node:fs";
const { readFile } = promises;

Overload 1

readFile(
path: PathLike | FileHandle,
options?: ({ encoding?: null | undefined; flag?: OpenMode | undefined; } & Abortable) | null,
): 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: PathLike | FileHandle

filename or FileHandle

options: ({ encoding?: null | undefined; flag?: OpenMode | undefined; } & Abortable) | null
optional

Return Type

Promise<Buffer>

Fulfills with the contents of the file.

Overload 2

readFile(
path: PathLike | FileHandle,
options: ({ encoding: BufferEncoding; flag?: OpenMode | undefined; } & Abortable) | BufferEncoding,
): Promise<string>

Asynchronously reads the entire contents of a file.

Parameters

path: PathLike | FileHandle

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: ({ encoding: BufferEncoding; flag?: OpenMode | undefined; } & Abortable) | BufferEncoding

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

Return Type

Promise<string>

Overload 3

readFile(
path: PathLike | FileHandle,
options?:
(
ObjectEncodingOptions
& Abortable
& { flag?: OpenMode | undefined; }
)

| BufferEncoding
| null
,
): Promise<string | Buffer>

Asynchronously reads the entire contents of a file.

Parameters

path: PathLike | FileHandle

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:
(
ObjectEncodingOptions
& Abortable
& { flag?: OpenMode | undefined; }
)

| BufferEncoding
| null
optional

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

Return Type

Promise<string | Buffer>

function promises.readlink

Usage in Deno

import { promises } from "node:fs";
const { readlink } = promises;

Overload 1

readlink(
path: PathLike,
options?:
ObjectEncodingOptions
| BufferEncoding
| null
,
): Promise<string>

Reads the contents of the symbolic link referred to by path. See the POSIX readlink(2) documentation for more detail. The promise is fulfilled with thelinkString upon success.

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 link path returned. If the encoding is set to 'buffer', the link path returned will be passed as a Buffer object.

Parameters

path: PathLike
options:
ObjectEncodingOptions
| BufferEncoding
| null
optional

Return Type

Promise<string>

Fulfills with the linkString upon success.

Overload 2

readlink(
path: PathLike,
options: BufferEncodingOption,
): Promise<Buffer>

Asynchronous readlink(2) - read value of a symbolic link.

Parameters

path: PathLike

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

options: BufferEncodingOption

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

Return Type

Promise<Buffer>

Overload 3

readlink(
path: PathLike,
options?:
ObjectEncodingOptions
| string
| null
,
): Promise<string | Buffer>

Asynchronous readlink(2) - read value of a symbolic link.

Parameters

path: PathLike

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

options:
ObjectEncodingOptions
| string
| null
optional

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

Return Type

Promise<string | Buffer>

function promises.realpath

Usage in Deno

import { promises } from "node:fs";
const { realpath } = promises;

Overload 1

realpath(
path: PathLike,
options?:
ObjectEncodingOptions
| BufferEncoding
| null
,
): Promise<string>

Determines the actual location of path using the same semantics as the fs.realpath.native() function.

Only paths that can be converted to UTF8 strings are supported.

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 path. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.

On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on /proc in order for this function to work. Glibc does not have this restriction.

Parameters

path: PathLike
options:
ObjectEncodingOptions
| BufferEncoding
| null
optional

Return Type

Promise<string>

Fulfills with the resolved path upon success.

Overload 2

realpath(
path: PathLike,
options: BufferEncodingOption,
): Promise<Buffer>

Asynchronous realpath(3) - return the canonicalized absolute pathname.

Parameters

path: PathLike

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

options: BufferEncodingOption

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

Return Type

Promise<Buffer>

Overload 3

realpath(
path: PathLike,
options?:
ObjectEncodingOptions
| BufferEncoding
| null
,
): Promise<string | Buffer>

Asynchronous realpath(3) - return the canonicalized absolute pathname.

Parameters

path: PathLike

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

options:
ObjectEncodingOptions
| BufferEncoding
| null
optional

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

Return Type

Promise<string | Buffer>

function promises.rename

Usage in Deno

import { promises } from "node:fs";
const { rename } = promises;
rename(
oldPath: PathLike,
newPath: PathLike,
): Promise<void>

Renames oldPath to newPath.

Parameters

oldPath: PathLike
newPath: PathLike

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.rm

Usage in Deno

import { promises } from "node:fs";
const { rm } = promises;
rm(
path: PathLike,
options?: RmOptions,
): Promise<void>

Removes files and directories (modeled on the standard POSIX rm utility).

Parameters

path: PathLike
options: RmOptions
optional

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.rmdir

Usage in Deno

import { promises } from "node:fs";
const { rmdir } = promises;
rmdir(
path: PathLike,
options?: RmDirOptions,
): 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 ENOTDIR error 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
options: RmDirOptions
optional

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.stat

Usage in Deno

import { promises } from "node:fs";
const { stat } = promises;

Overload 1

stat(
path: PathLike,
opts?: StatOptions & { bigint?: false | undefined; },
): Promise<Stats>

Parameters

path: PathLike
opts: StatOptions & { bigint?: false | undefined; }
optional

Return Type

Promise<Stats>

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

Overload 2

stat(
path: PathLike,
opts: StatOptions & { bigint: true; },
): Promise<BigIntStats>

Parameters

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

Return Type

Promise<BigIntStats>

Overload 3

stat(
path: PathLike,
opts?: StatOptions,
): Promise<Stats | BigIntStats>

Parameters

path: PathLike
opts: StatOptions
optional

Return Type

Promise<Stats | BigIntStats>

function promises.statfs

Usage in Deno

import { promises } from "node:fs";
const { statfs } = promises;

Overload 1

statfs(
path: PathLike,
opts?: StatFsOptions & { bigint?: false | undefined; },
): Promise<StatsFs>

Parameters

path: PathLike
opts: StatFsOptions & { bigint?: false | undefined; }
optional

Return Type

Promise<StatsFs>

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

Overload 2

statfs(
path: PathLike,
opts: StatFsOptions & { bigint: true; },
): Promise<BigIntStatsFs>

Parameters

path: PathLike
opts: StatFsOptions & { bigint: true; }

Return Type

Promise<BigIntStatsFs>

Overload 3

statfs(
path: PathLike,
opts?: StatFsOptions,
): Promise<StatsFs | BigIntStatsFs>

Parameters

path: PathLike
opts: StatFsOptions
optional

Return Type

Promise<StatsFs | BigIntStatsFs>

function promises.symlink

Usage in Deno

import { promises } from "node:fs";
const { symlink } = promises;
symlink(
target: PathLike,
path: PathLike,
type?: string | null,
): Promise<void>

Creates a symbolic link.

The type argument is only used on Windows platforms and can be one of 'dir', 'file', or 'junction'. If the type argument is not a string, Node.js will autodetect target type and use 'file' or 'dir'. If the target does not exist, 'file' will be used. Windows junction points require the destination path to be absolute. When using 'junction', the target argument will automatically be normalized to absolute path. Junction points on NTFS volumes can only point to directories.

Parameters

target: PathLike
path: PathLike
type: string | null = 'null'
optional

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.truncate

Usage in Deno

import { promises } from "node:fs";
const { truncate } = promises;
truncate(
path: PathLike,
len?: number,
): Promise<void>

Truncates (shortens or extends the length) of the content at path to len bytes.

Parameters

path: PathLike
len: number = 0
optional

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.unlink

Usage in Deno

import { promises } from "node:fs";
const { unlink } = promises;
unlink(path: PathLike): Promise<void>

If path refers to a symbolic link, then the link is removed without affecting the file or directory to which that link refers. If the path refers to a file path that is not a symbolic link, the file is deleted. See the POSIX unlink(2) documentation for more detail.

Parameters

path: PathLike

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.utimes

Usage in Deno

import { promises } from "node:fs";
const { utimes } = promises;
utimes(
path: PathLike,
atime: TimeLike,
mtime: TimeLike,
): Promise<void>

Change the file system timestamps of the object referenced by path.

The atime and mtime arguments follow these rules:

  • Values can be either numbers representing Unix epoch time, Dates, or a numeric string like '123456789.0'.
  • If the value can not be converted to a number, or is NaN, Infinity, or -Infinity, an Error will be thrown.

Parameters

path: PathLike
atime: TimeLike
mtime: TimeLike

Return Type

Promise<void>

Fulfills with undefined upon success.


function promises.watch

Usage in Deno

import { promises } from "node:fs";
const { watch } = promises;

Overload 1

watch(
filename: PathLike,
options: (WatchOptions & { encoding: "buffer"; }) | "buffer",
): AsyncIterable<FileChangeInfo<Buffer>>

Returns an async iterator that watches for changes on filename, where filenameis either a file or a directory.

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

const ac = new AbortController();
const { signal } = ac;
setTimeout(() => ac.abort(), 10000);

(async () => {
  try {
    const watcher = watch(__filename, { signal });
    for await (const event of watcher)
      console.log(event);
  } catch (err) {
    if (err.name === 'AbortError')
      return;
    throw err;
  }
})();

On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.

All the caveats for fs.watch() also apply to fsPromises.watch().

Parameters

filename: PathLike
options: (WatchOptions & { encoding: "buffer"; }) | "buffer"

Return Type

AsyncIterable<FileChangeInfo<Buffer>>

of objects with the properties:

Overload 2

watch(
filename: PathLike,
options?: WatchOptions | BufferEncoding,
): AsyncIterable<FileChangeInfo<string>>

Watch for changes on filename, where filename is either a file or a directory, returning an FSWatcher.

Parameters

filename: PathLike

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

options: WatchOptions | BufferEncoding
optional

Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. If encoding is not supplied, the default of 'utf8' is used. If persistent is not supplied, the default of true is used. If recursive is not supplied, the default of false is used.

Return Type

AsyncIterable<FileChangeInfo<string>>

Overload 3

watch(
filename: PathLike,
options: WatchOptions | string,
): AsyncIterable<FileChangeInfo<string>> | AsyncIterable<FileChangeInfo<Buffer>>

Watch for changes on filename, where filename is either a file or a directory, returning an FSWatcher.

Parameters

filename: PathLike

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

options: WatchOptions | string

Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. If encoding is not supplied, the default of 'utf8' is used. If persistent is not supplied, the default of true is used. If recursive is not supplied, the default of false is used.

Return Type

AsyncIterable<FileChangeInfo<string>> | AsyncIterable<FileChangeInfo<Buffer>>

function promises.writeFile

Usage in Deno

import { promises } from "node:fs";
const { writeFile } = promises;
writeFile(
file: PathLike | FileHandle,
data:
string
| ArrayBufferView
| Iterable<string | ArrayBufferView>
| AsyncIterable<string | ArrayBufferView>
| Stream
,
options?:
(
ObjectEncodingOptions
& { mode?: Mode | undefined; flag?: OpenMode | undefined; flush?: boolean | undefined; }
& Abortable
)

| BufferEncoding
| null
,
): 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: PathLike | FileHandle

filename or FileHandle

data:
string
| ArrayBufferView
| Iterable<string | ArrayBufferView>
| AsyncIterable<string | ArrayBufferView>
| Stream
options:
(
ObjectEncodingOptions
& { mode?: Mode | undefined; flag?: OpenMode | undefined; flush?: boolean | undefined; }
& Abortable
)

| BufferEncoding
| null
optional

Return Type

Promise<void>

Fulfills with undefined upon success.


function read

Usage in Deno

import { read } from "node:fs";

Overload 1

read<TBuffer extends ArrayBufferView>(
fd: number,
buffer: TBuffer,
offset: number,
length: number,
position: ReadPosition | null,
callback: (
err: ErrnoException | null,
bytesRead: number,
buffer: TBuffer,
) => void
,
): void

Read data from the file specified by fd.

The callback is given the three arguments, (err, bytesRead, buffer).

If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.

If this method is invoked as its util.promisify() ed version, it returns a promise for an Object with bytesRead and buffer properties.

Type Parameters

TBuffer extends ArrayBufferView

Parameters

fd: number
buffer: TBuffer

The buffer that the data will be written to.

offset: number

The position in buffer to write the data to.

length: number

The number of bytes to read.

position: ReadPosition | null

Specifies where to begin reading from in the file. If position is null or -1 , data will be read from the current file position, and the file position will be updated. If position is an integer, the file position will be unchanged.

callback: (
err: ErrnoException | null,
bytesRead: number,
buffer: TBuffer,
) => void

Return Type

void

Overload 2

read<TBuffer extends ArrayBufferView>(
fd: number,
options: ReadAsyncOptions<TBuffer>,
callback: (
err: ErrnoException | null,
bytesRead: number,
buffer: TBuffer,
) => void
,
): void

Similar to the above fs.read function, this version takes an optional options object. If not otherwise specified in an options object, buffer defaults to Buffer.alloc(16384), offset defaults to 0, length defaults to buffer.byteLength, - offset as of Node 17.6.0 position defaults to null

Type Parameters

TBuffer extends ArrayBufferView

Parameters

fd: number
options: ReadAsyncOptions<TBuffer>
callback: (
err: ErrnoException | null,
bytesRead: number,
buffer: TBuffer,
) => void

Return Type

void

Overload 3

read<TBuffer extends ArrayBufferView>(
fd: number,
buffer: TBuffer,
options: ReadSyncOptions,
callback: (
err: ErrnoException | null,
bytesRead: number,
buffer: TBuffer,
) => void
,
): void

Type Parameters

TBuffer extends ArrayBufferView

Parameters

fd: number
buffer: TBuffer
options: ReadSyncOptions
callback: (
err: ErrnoException | null,
bytesRead: number,
buffer: TBuffer,
) => void

Return Type

void

Overload 4

read<TBuffer extends ArrayBufferView>(
fd: number,
buffer: TBuffer,
callback: (
err: ErrnoException | null,
bytesRead: number,
buffer: TBuffer,
) => void
,
): void

Type Parameters

TBuffer extends ArrayBufferView

Parameters

fd: number
buffer: TBuffer
callback: (
err: ErrnoException | null,
bytesRead: number,
buffer: TBuffer,
) => void

Return Type

void

Overload 5

read(
fd: number,
callback: (
err: ErrnoException | null,
bytesRead: number,
buffer: ArrayBufferView,
) => void
,
): void

Parameters

fd: number
callback: (
err: ErrnoException | null,
bytesRead: number,
buffer: ArrayBufferView,
) => void

Return Type

void

function readdir

Usage in Deno

import { readdir } from "node:fs";

Overload 1

readdir(
path: PathLike,
options:
{ encoding: BufferEncoding | null; withFileTypes?: false | undefined; recursive?: boolean | undefined; }
| BufferEncoding
| undefined
| null
,
callback: (
err: ErrnoException | null,
files: string[],
) => void
,
): void

Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.

See the POSIX readdir(3) documentation for more details.

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 passed to the callback. If the encoding is set to 'buffer', the filenames returned will be passed as Buffer objects.

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

Parameters

path: PathLike
options:
{ encoding: BufferEncoding | null; withFileTypes?: false | undefined; recursive?: boolean | undefined; }
| BufferEncoding
| undefined
| null
callback: (
err: ErrnoException | null,
files: string[],
) => void

Return Type

void

Overload 2

readdir(
path: PathLike,
options: { encoding: "buffer"; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | "buffer",
callback: (
err: ErrnoException | null,
files: Buffer[],
) => void
,
): void

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: { encoding: "buffer"; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | "buffer"

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

callback: (
err: ErrnoException | null,
files: Buffer[],
) => void

Return Type

void

Overload 3

readdir(
path: PathLike,
options:
(ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| undefined
| null
,
callback: (
err: ErrnoException | null,
files: string[] | Buffer[],
) => void
,
): void

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 & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| undefined
| null

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

callback: (
err: ErrnoException | null,
files: string[] | Buffer[],
) => void

Return Type

void

Overload 4

readdir(
path: PathLike,
callback: (
err: ErrnoException | null,
files: string[],
) => void
,
): void

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.

callback: (
err: ErrnoException | null,
files: string[],
) => void

Return Type

void

Overload 5

readdir(
path: PathLike,
options: ObjectEncodingOptions & { withFileTypes: true; recursive?: boolean | undefined; },
callback: (
err: ErrnoException | null,
files: Dirent[],
) => void
,
): void

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 & { withFileTypes: true; recursive?: boolean | undefined; }

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

callback: (
err: ErrnoException | null,
files: Dirent[],
) => void

Return Type

void

function readdirSync

Usage in Deno

import { readdirSync } from "node:fs";

Overload 1

readdirSync(
path: PathLike,
options?:
{ encoding: BufferEncoding | null; withFileTypes?: false | undefined; recursive?: boolean | undefined; }
| BufferEncoding
| null
,
): string[]

Reads the contents of the directory.

See the POSIX readdir(3) documentation for more details.

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 returned. If the encoding is set to 'buffer', the filenames returned will be passed as Buffer objects.

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

Parameters

path: PathLike
options:
{ encoding: BufferEncoding | null; withFileTypes?: false | undefined; recursive?: boolean | undefined; }
| BufferEncoding
| null
optional

Return Type

string[]

Overload 2

readdirSync(
path: PathLike,
options: { encoding: "buffer"; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | "buffer",
): Buffer[]

Synchronous 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: { encoding: "buffer"; withFileTypes?: false | undefined; recursive?: boolean | undefined; } | "buffer"

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

Return Type

Buffer[]

Overload 3

readdirSync(
path: PathLike,
options?:
(ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| null
,
): string[] | Buffer[]

Synchronous 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 & { withFileTypes?: false | undefined; recursive?: boolean | undefined; })
| BufferEncoding
| null
optional

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

Return Type

string[] | Buffer[]

Overload 4

readdirSync(
path: PathLike,
options: ObjectEncodingOptions & { withFileTypes: true; recursive?: boolean | undefined; },
): Dirent[]

Synchronous 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 & { withFileTypes: true; recursive?: boolean | undefined; }

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

Return Type

Dirent[]

function readFile

Usage in Deno

import { readFile } from "node:fs";

Overload 1

readFile(
path: PathOrFileDescriptor,
options:
({ encoding?: null | undefined; flag?: string | undefined; } & Abortable)
| undefined
| null
,
callback: (
err: ErrnoException | null,
data: Buffer,
) => void
,
): void

Asynchronously reads the entire contents of a file.

import { readFile } from 'node:fs';

readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});

The callback is passed two arguments (err, data), where data is the contents of the file.

If no encoding is specified, then the raw buffer is returned.

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

import { readFile } from 'node:fs';

readFile('/etc/passwd', 'utf8', callback);

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

import { readFile } from 'node:fs';

// macOS, Linux, and Windows
readFile('<directory>', (err, data) => {
  // => [Error: EISDIR: illegal operation on a directory, read <directory>]
});

//  FreeBSD
readFile('<directory>', (err, data) => {
  // => null, <data>
});

It is possible to abort an ongoing request using an AbortSignal. If a request is aborted the callback is called with an AbortError:

import { readFile } from 'node:fs';

const controller = new AbortController();
const signal = controller.signal;
readFile(fileInfo[0].name, { signal }, (err, buf) => {
  // ...
});
// When you want to abort the request
controller.abort();

The fs.readFile() function buffers the entire file. To minimize memory costs, when possible prefer streaming via fs.createReadStream().

Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.readFile performs.

Parameters

path: PathOrFileDescriptor

filename or file descriptor

options:
({ encoding?: null | undefined; flag?: string | undefined; } & Abortable)
| undefined
| null
callback: (
err: ErrnoException | null,
data: Buffer,
) => void

Return Type

void

Overload 2

readFile(
path: PathOrFileDescriptor,
options: ({ encoding: BufferEncoding; flag?: string | undefined; } & Abortable) | BufferEncoding,
callback: (
err: ErrnoException | null,
data: string,
) => void
,
): void

Asynchronously reads the entire contents of a file.

Parameters

path: PathOrFileDescriptor

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

options: ({ encoding: BufferEncoding; flag?: string | undefined; } & Abortable) | BufferEncoding

Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'.

callback: (
err: ErrnoException | null,
data: string,
) => void

Return Type

void

Overload 3

readFile(
path: PathOrFileDescriptor,
options:
(
ObjectEncodingOptions
& { flag?: string | undefined; }
& Abortable
)

| BufferEncoding
| undefined
| null
,
callback: (
err: ErrnoException | null,
data: string | Buffer,
) => void
,
): void

Asynchronously reads the entire contents of a file.

Parameters

path: PathOrFileDescriptor

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

options:
(
ObjectEncodingOptions
& { flag?: string | undefined; }
& Abortable
)

| BufferEncoding
| undefined
| null

Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'.

callback: (
err: ErrnoException | null,
data: string | Buffer,
) => void

Return Type

void

Overload 4

readFile(
path: PathOrFileDescriptor,
callback: (
err: ErrnoException | null,
data: Buffer,
) => void
,
): void

Asynchronously reads the entire contents of a file.

Parameters

path: PathOrFileDescriptor

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

callback: (
err: ErrnoException | null,
data: Buffer,
) => void

Return Type

void

function readFileSync

Usage in Deno

import { readFileSync } from "node:fs";

Overload 1

readFileSync(
path: PathOrFileDescriptor,
options?: { encoding?: null | undefined; flag?: string | undefined; } | null,
): Buffer

Returns the contents of the path.

For detailed information, see the documentation of the asynchronous version of this API: readFile.

If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.

Similar to readFile, when the path is a directory, the behavior of fs.readFileSync() is platform-specific.

import { readFileSync } from 'node:fs';

// macOS, Linux, and Windows
readFileSync('<directory>');
// => [Error: EISDIR: illegal operation on a directory, read <directory>]

//  FreeBSD
readFileSync('<directory>'); // => <data>

Parameters

path: PathOrFileDescriptor

filename or file descriptor

options: { encoding?: null | undefined; flag?: string | undefined; } | null
optional

Return Type

Buffer

Overload 2

readFileSync(
path: PathOrFileDescriptor,
options: { encoding: BufferEncoding; flag?: string | undefined; } | BufferEncoding,
): string

Synchronously reads the entire contents of a file.

Parameters

path: PathOrFileDescriptor

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

options: { encoding: BufferEncoding; flag?: string | undefined; } | BufferEncoding

Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'.

Return Type

string

Overload 3

readFileSync(
path: PathOrFileDescriptor,
options?:
(ObjectEncodingOptions & { flag?: string | undefined; })
| BufferEncoding
| null
,
): string | Buffer

Synchronously reads the entire contents of a file.

Parameters

path: PathOrFileDescriptor

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

options:
(ObjectEncodingOptions & { flag?: string | undefined; })
| BufferEncoding
| null
optional

Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'.

Return Type

string | Buffer

function readlink

Usage in Deno

import { readlink } from "node:fs";

Overload 1

readlink(
path: PathLike,
options: EncodingOption,
callback: (
err: ErrnoException | null,
linkString: string,
) => void
,
): void

Reads the contents of the symbolic link referred to by path. The callback gets two arguments (err, linkString).

See the POSIX readlink(2) documentation for more details.

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 link path passed to the callback. If the encoding is set to 'buffer', the link path returned will be passed as a Buffer object.

Parameters

path: PathLike
options: EncodingOption
callback: (
err: ErrnoException | null,
linkString: string,
) => void

Return Type

void

Overload 2

readlink(
path: PathLike,
options: BufferEncodingOption,
callback: (
err: ErrnoException | null,
linkString: Buffer,
) => void
,
): void

Asynchronous readlink(2) - read value of a symbolic link.

Parameters

path: PathLike

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

options: BufferEncodingOption

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

callback: (
err: ErrnoException | null,
linkString: Buffer,
) => void

Return Type

void

Overload 3

readlink(
path: PathLike,
options: EncodingOption,
callback: (
err: ErrnoException | null,
linkString: string | Buffer,
) => void
,
): void

Asynchronous readlink(2) - read value of a symbolic link.

Parameters

path: PathLike

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

options: EncodingOption

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

callback: (
err: ErrnoException | null,
linkString: string | Buffer,
) => void

Return Type

void

Overload 4

readlink(
path: PathLike,
callback: (
err: ErrnoException | null,
linkString: string,
) => void
,
): void

Asynchronous readlink(2) - read value of a symbolic link.

Parameters

path: PathLike

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

callback: (
err: ErrnoException | null,
linkString: string,
) => void

Return Type

void

function readlinkSync

Usage in Deno

import { readlinkSync } from "node:fs";

Overload 1

readlinkSync(
path: PathLike,
options?: EncodingOption,
): string

Returns the symbolic link's string value.

See the POSIX readlink(2) documentation for more details.

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 link path returned. If the encoding is set to 'buffer', the link path returned will be passed as a Buffer object.

Parameters

path: PathLike
options: EncodingOption
optional

Return Type

string

Overload 2

readlinkSync(
path: PathLike,
options: BufferEncodingOption,
): Buffer

Synchronous readlink(2) - read value of a symbolic link.

Parameters

path: PathLike

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

options: BufferEncodingOption

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

Return Type

Buffer

Overload 3

readlinkSync(
path: PathLike,
options?: EncodingOption,
): string | Buffer

Synchronous readlink(2) - read value of a symbolic link.

Parameters

path: PathLike

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

options: EncodingOption
optional

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

Return Type

string | Buffer

function readSync

Usage in Deno

import { readSync } from "node:fs";

Overload 1

readSync(
fd: number,
buffer: ArrayBufferView,
offset: number,
length: number,
position: ReadPosition | null,
): number

Returns the number of bytesRead.

For detailed information, see the documentation of the asynchronous version of this API: read.

Parameters

fd: number
buffer: ArrayBufferView
offset: number
length: number
position: ReadPosition | null = 'null'
optional

Return Type

number

Overload 2

readSync(
fd: number,
buffer: ArrayBufferView,
opts?: ReadSyncOptions,
): number

Similar to the above fs.readSync function, this version takes an optional options object. If no options object is specified, it will default with the above values.

Parameters

fd: number
buffer: ArrayBufferView
opts: ReadSyncOptions
optional

Return Type

number

function readv

Usage in Deno

import { readv } from "node:fs";

Overload 1

readv(
fd: number,
buffers: readonly ArrayBufferView[],
cb: (
err: ErrnoException | null,
bytesRead: number,
buffers: ArrayBufferView[],
) => void
,
): void

Read from a file specified by fd and write to an array of ArrayBufferViews using readv().

position is the offset from the beginning of the file from where data should be read. If typeof position !== 'number', the data will be read from the current position.

The callback will be given three arguments: err, bytesRead, and buffers. bytesRead is how many bytes were read from the file.

If this method is invoked as its util.promisify() ed version, it returns a promise for an Object with bytesRead and buffers properties.

Parameters

fd: number
buffers: readonly ArrayBufferView[]
cb: (
err: ErrnoException | null,
bytesRead: number,
buffers: ArrayBufferView[],
) => void

Return Type

void

Overload 2

readv(
fd: number,
buffers: readonly ArrayBufferView[],
position: number | null,
cb: (
err: ErrnoException | null,
bytesRead: number,
buffers: ArrayBufferView[],
) => void
,
): void

Parameters

fd: number
buffers: readonly ArrayBufferView[]
position: number | null
cb: (
err: ErrnoException | null,
bytesRead: number,
buffers: ArrayBufferView[],
) => void

Return Type

void

function readvSync

Usage in Deno

import { readvSync } from "node:fs";
readvSync(
fd: number,
buffers: readonly ArrayBufferView[],
position?: number,
): number

For detailed information, see the documentation of the asynchronous version of this API: readv.

Parameters

fd: number
buffers: readonly ArrayBufferView[]
position: number = 'null'
optional

Return Type

number

The number of bytes read.


function realpath

Usage in Deno

import { realpath } from "node:fs";

Overload 1

realpath(
path: PathLike,
options: EncodingOption,
callback: (
err: ErrnoException | null,
resolvedPath: string,
) => void
,
): void

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

A canonical pathname is not necessarily unique. Hard links and bind mounts can expose a file system entity through many pathnames.

This function behaves like realpath(3), with some exceptions:

  1. No case conversion is performed on case-insensitive file systems.
  2. The maximum number of symbolic links is platform-independent and generally (much) higher than what the native realpath(3) implementation supports.

The callback gets two arguments (err, resolvedPath). May use process.cwd to resolve relative paths.

Only paths that can be converted to UTF8 strings are supported.

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 path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.

If path resolves to a socket or a pipe, the function will return a system dependent name for that object.

Parameters

path: PathLike
options: EncodingOption
callback: (
err: ErrnoException | null,
resolvedPath: string,
) => void

Return Type

void

Overload 2

realpath(
path: PathLike,
options: BufferEncodingOption,
callback: (
err: ErrnoException | null,
resolvedPath: Buffer,
) => void
,
): void

Asynchronous realpath(3) - return the canonicalized absolute pathname.

Parameters

path: PathLike

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

options: BufferEncodingOption

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

callback: (
err: ErrnoException | null,
resolvedPath: Buffer,
) => void

Return Type

void

Overload 3

realpath(
path: PathLike,
options: EncodingOption,
callback: (
err: ErrnoException | null,
resolvedPath: string | Buffer,
) => void
,
): void

Asynchronous realpath(3) - return the canonicalized absolute pathname.

Parameters

path: PathLike

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

options: EncodingOption

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

callback: (
err: ErrnoException | null,
resolvedPath: string | Buffer,
) => void

Return Type

void

Overload 4

realpath(
path: PathLike,
callback: (
err: ErrnoException | null,
resolvedPath: string,
) => void
,
): void

Asynchronous realpath(3) - return the canonicalized absolute pathname.

Parameters

path: PathLike

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

callback: (
err: ErrnoException | null,
resolvedPath: string,
) => void

Return Type

void

namespace realpath

Functions

realpath.native

Asynchronous realpath(3).


function realpath.native

Usage in Deno

import { realpath } from "node:fs";

Overload 1

native(
path: PathLike,
options: EncodingOption,
callback: (
err: ErrnoException | null,
resolvedPath: string,
) => void
,
): void

Asynchronous realpath(3).

The callback gets two arguments (err, resolvedPath).

Only paths that can be converted to UTF8 strings are supported.

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 path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.

On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on /proc in order for this function to work. Glibc does not have this restriction.

Parameters

path: PathLike
options: EncodingOption
callback: (
err: ErrnoException | null,
resolvedPath: string,
) => void

Return Type

void

Overload 2

native(
path: PathLike,
options: BufferEncodingOption,
callback: (
err: ErrnoException | null,
resolvedPath: Buffer,
) => void
,
): void

Parameters

path: PathLike
options: BufferEncodingOption
callback: (
err: ErrnoException | null,
resolvedPath: Buffer,
) => void

Return Type

void

Overload 3

native(
path: PathLike,
options: EncodingOption,
callback: (
err: ErrnoException | null,
resolvedPath: string | Buffer,
) => void
,
): void

Parameters

path: PathLike
options: EncodingOption
callback: (
err: ErrnoException | null,
resolvedPath: string | Buffer,
) => void

Return Type

void

Overload 4

native(
path: PathLike,
callback: (
err: ErrnoException | null,
resolvedPath: string,
) => void
,
): void

Parameters

path: PathLike
callback: (
err: ErrnoException | null,
resolvedPath: string,
) => void

Return Type

void

function realpathSync

Usage in Deno

import { realpathSync } from "node:fs";

Overload 1

realpathSync(
path: PathLike,
options?: EncodingOption,
): string

Returns the resolved pathname.

For detailed information, see the documentation of the asynchronous version of this API: realpath.

Parameters

path: PathLike
options: EncodingOption
optional

Return Type

string

Overload 2

realpathSync(
path: PathLike,
options: BufferEncodingOption,
): Buffer

Synchronous realpath(3) - return the canonicalized absolute pathname.

Parameters

path: PathLike

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

options: BufferEncodingOption

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

Return Type

Buffer

Overload 3

realpathSync(
path: PathLike,
options?: EncodingOption,
): string | Buffer

Synchronous realpath(3) - return the canonicalized absolute pathname.

Parameters

path: PathLike

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

options: EncodingOption
optional

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

Return Type

string | Buffer

namespace realpathSync

Functions

realpathSync.native
No documentation available

function realpathSync.native

Usage in Deno

import { realpathSync } from "node:fs";

Overload 1

native(
path: PathLike,
options?: EncodingOption,
): string

Parameters

path: PathLike
options: EncodingOption
optional

Return Type

string

Overload 2

native(
path: PathLike,
options: BufferEncodingOption,
): Buffer

Parameters

path: PathLike
options: BufferEncodingOption

Return Type

Buffer

Overload 3

native(
path: PathLike,
options?: EncodingOption,
): string | Buffer

Parameters

path: PathLike
options: EncodingOption
optional

Return Type

string | Buffer

function rename

Usage in Deno

import { rename } from "node:fs";
rename(
oldPath: PathLike,
newPath: PathLike,
callback: NoParamCallback,
): void

Asynchronously rename file at oldPath to the pathname provided as newPath. In the case that newPath already exists, it will be overwritten. If there is a directory at newPath, an error will be raised instead. No arguments other than a possible exception are given to the completion callback.

See also: rename(2).

import { rename } from 'node:fs';

rename('oldFile.txt', 'newFile.txt', (err) => {
  if (err) throw err;
  console.log('Rename complete!');
});

Parameters

oldPath: PathLike
newPath: PathLike
callback: NoParamCallback

Return Type

void

function renameSync

Usage in Deno

import { renameSync } from "node:fs";
renameSync(
oldPath: PathLike,
newPath: PathLike,
): void

Renames the file from oldPath to newPath. Returns undefined.

See the POSIX rename(2) documentation for more details.

Parameters

oldPath: PathLike
newPath: PathLike

Return Type

void

function rm

Usage in Deno

import { rm } from "node:fs";

Overload 1

rm(
path: PathLike,
callback: NoParamCallback,
): void

Asynchronously removes files and directories (modeled on the standard POSIX rm utility). No arguments other than a possible exception are given to the completion callback.

Parameters

path: PathLike
callback: NoParamCallback

Return Type

void

Overload 2

rm(
path: PathLike,
options: RmOptions,
callback: NoParamCallback,
): void

Parameters

path: PathLike
options: RmOptions
callback: NoParamCallback

Return Type

void

function rmdir

Usage in Deno

import { rmdir } from "node:fs";

Overload 1

rmdir(
path: PathLike,
callback: NoParamCallback,
): void

Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.

Using fs.rmdir() on a file (not a directory) results in an ENOENT error on Windows and an ENOTDIR error on POSIX.

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

Parameters

path: PathLike
callback: NoParamCallback

Return Type

void

Overload 2

rmdir(
path: PathLike,
options: RmDirOptions,
callback: NoParamCallback,
): void

Parameters

path: PathLike
options: RmDirOptions
callback: NoParamCallback

Return Type

void

function rmdirSync

Usage in Deno

import { rmdirSync } from "node:fs";
rmdirSync(
path: PathLike,
options?: RmDirOptions,
): void

Synchronous rmdir(2). Returns undefined.

Using fs.rmdirSync() on a file (not a directory) results in an ENOENT error on Windows and an ENOTDIR error on POSIX.

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

Parameters

path: PathLike
options: RmDirOptions
optional

Return Type

void

function rmSync

Usage in Deno

import { rmSync } from "node:fs";
rmSync(
path: PathLike,
options?: RmOptions,
): void

Synchronously removes files and directories (modeled on the standard POSIX rm utility). Returns undefined.

Parameters

path: PathLike
options: RmOptions
optional

Return Type

void

function stat

Usage in Deno

import { stat } from "node:fs";

Overload 1

stat(
path: PathLike,
callback: (
err: ErrnoException | null,
stats: Stats,
) => void
,
): void

Asynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.

In case of an error, the err.code will be one of Common System Errors.

stat follows symbolic links. Use lstat to look at the links themselves.

Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.

To check if a file exists without manipulating it afterwards, access is recommended.

For example, given the following directory structure:

- txtDir
-- file.txt
- app.js

The next program will check for the stats of the given paths:

import { stat } from 'node:fs';

const pathsToCheck = ['./txtDir', './txtDir/file.txt'];

for (let i = 0; i < pathsToCheck.length; i++) {
  stat(pathsToCheck[i], (err, stats) => {
    console.log(stats.isDirectory());
    console.log(stats);
  });
}

The resulting output will resemble:

true
Stats {
  dev: 16777220,
  mode: 16877,
  nlink: 3,
  uid: 501,
  gid: 20,
  rdev: 0,
  blksize: 4096,
  ino: 14214262,
  size: 96,
  blocks: 0,
  atimeMs: 1561174653071.963,
  mtimeMs: 1561174614583.3518,
  ctimeMs: 1561174626623.5366,
  birthtimeMs: 1561174126937.2893,
  atime: 2019-06-22T03:37:33.072Z,
  mtime: 2019-06-22T03:36:54.583Z,
  ctime: 2019-06-22T03:37:06.624Z,
  birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
  dev: 16777220,
  mode: 33188,
  nlink: 1,
  uid: 501,
  gid: 20,
  rdev: 0,
  blksize: 4096,
  ino: 14214074,
  size: 8,
  blocks: 8,
  atimeMs: 1561174616618.8555,
  mtimeMs: 1561174614584,
  ctimeMs: 1561174614583.8145,
  birthtimeMs: 1561174007710.7478,
  atime: 2019-06-22T03:36:56.619Z,
  mtime: 2019-06-22T03:36:54.584Z,
  ctime: 2019-06-22T03:36:54.584Z,
  birthtime: 2019-06-22T03:26:47.711Z
}

Parameters

path: PathLike
callback: (
err: ErrnoException | null,
stats: Stats,
) => void

Return Type

void

Overload 2

stat(
path: PathLike,
options: (StatOptions & { bigint?: false | undefined; }) | undefined,
callback: (
err: ErrnoException | null,
stats: Stats,
) => void
,
): void

Parameters

path: PathLike
options: (StatOptions & { bigint?: false | undefined; }) | undefined
callback: (
err: ErrnoException | null,
stats: Stats,
) => void

Return Type

void

Overload 3

stat(
path: PathLike,
options: StatOptions & { bigint: true; },
callback: (
err: ErrnoException | null,
stats: BigIntStats,
) => void
,
): void

Parameters

path: PathLike
options: StatOptions & { bigint: true; }
callback: (
err: ErrnoException | null,
stats: BigIntStats,
) => void

Return Type

void

Overload 4

stat(
path: PathLike,
options: StatOptions | undefined,
callback: (
err: ErrnoException | null,
stats: Stats | BigIntStats,
) => void
,
): void

Parameters

path: PathLike
options: StatOptions | undefined
callback: (
err: ErrnoException | null,
stats: Stats | BigIntStats,
) => void

Return Type

void

function statfs

Usage in Deno

import { statfs } from "node:fs";

Overload 1

statfs(
path: PathLike,
callback: (
err: ErrnoException | null,
stats: StatsFs,
) => void
,
): void

Asynchronous statfs(2). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where statsis an fs.StatFs object.

In case of an error, the err.code will be one of Common System Errors.

Parameters

path: PathLike

A path to an existing file or directory on the file system to be queried.

callback: (
err: ErrnoException | null,
stats: StatsFs,
) => void

Return Type

void

Overload 2

statfs(
path: PathLike,
options: (StatFsOptions & { bigint?: false | undefined; }) | undefined,
callback: (
err: ErrnoException | null,
stats: StatsFs,
) => void
,
): void

Parameters

path: PathLike
options: (StatFsOptions & { bigint?: false | undefined; }) | undefined
callback: (
err: ErrnoException | null,
stats: StatsFs,
) => void

Return Type

void

Overload 3

statfs(
path: PathLike,
options: StatFsOptions & { bigint: true; },
callback: (
err: ErrnoException | null,
stats: BigIntStatsFs,
) => void
,
): void

Parameters

path: PathLike
options: StatFsOptions & { bigint: true; }
callback: (
err: ErrnoException | null,
stats: BigIntStatsFs,
) => void

Return Type

void

Overload 4

statfs(
path: PathLike,
options: StatFsOptions | undefined,
callback: (
err: ErrnoException | null,
stats: StatsFs | BigIntStatsFs,
) => void
,
): void

Parameters

path: PathLike
options: StatFsOptions | undefined
callback: (
err: ErrnoException | null,
stats: StatsFs | BigIntStatsFs,
) => void

Return Type

void

function statfsSync

Usage in Deno

import { statfsSync } from "node:fs";

Overload 1

statfsSync(
path: PathLike,
options?: StatFsOptions & { bigint?: false | undefined; },
): StatsFs

Synchronous statfs(2). Returns information about the mounted file system which contains path.

In case of an error, the err.code will be one of Common System Errors.

Parameters

path: PathLike

A path to an existing file or directory on the file system to be queried.

options: StatFsOptions & { bigint?: false | undefined; }
optional

Return Type

StatsFs

Overload 2

statfsSync(
path: PathLike,
options: StatFsOptions & { bigint: true; },
): BigIntStatsFs

Parameters

path: PathLike
options: StatFsOptions & { bigint: true; }

Return Type

BigIntStatsFs

Overload 3

statfsSync(
path: PathLike,
options?: StatFsOptions,
): StatsFs | BigIntStatsFs

Parameters

path: PathLike
options: StatFsOptions
optional

Return Type

StatsFs | BigIntStatsFs

function symlink

Usage in Deno

import { symlink } from "node:fs";

Overload 1

symlink(
target: PathLike,
path: PathLike,
type:
symlink.Type
| undefined
| null
,
callback: NoParamCallback,
): void

Creates the link called path pointing to target. No arguments other than a possible exception are given to the completion callback.

See the POSIX symlink(2) documentation for more details.

The type argument is only available on Windows and ignored on other platforms. It can be set to 'dir', 'file', or 'junction'. If the type argument is not a string, Node.js will autodetect target type and use 'file' or 'dir'. If the target does not exist, 'file' will be used. Windows junction points require the destination path to be absolute. When using 'junction', thetarget argument will automatically be normalized to absolute path. Junction points on NTFS volumes can only point to directories.

Relative targets are relative to the link's parent directory.

import { symlink } from 'node:fs';

symlink('./mew', './mewtwo', callback);

The above example creates a symbolic link mewtwo which points to mew in the same directory:

$ tree .
.
├── mew
└── mewtwo -> ./mew

Parameters

target: PathLike
path: PathLike
type:
symlink.Type
| undefined
| null
= 'null'
optional
callback: NoParamCallback

Return Type

void

Overload 2

symlink(
target: PathLike,
path: PathLike,
callback: NoParamCallback,
): void

Asynchronous symlink(2) - Create a new symbolic link to an existing file.

Parameters

target: PathLike

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

path: PathLike

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

callback: NoParamCallback

Return Type

void

namespace symlink

Type Aliases

symlink.Type
No documentation available

function symlinkSync

Usage in Deno

import { symlinkSync } from "node:fs";
symlinkSync(
target: PathLike,
path: PathLike,
type?: symlink.Type | null,
): void

Returns undefined.

For detailed information, see the documentation of the asynchronous version of this API: symlink.

Parameters

target: PathLike
path: PathLike
type: symlink.Type | null = 'null'
optional

Return Type

void

function truncate

Usage in Deno

import { truncate } from "node:fs";

Overload 1

truncate(
path: PathLike,
len: number | undefined,
callback: NoParamCallback,
): void

Truncates the file. No arguments other than a possible exception are given to the completion callback. A file descriptor can also be passed as the first argument. In this case, fs.ftruncate() is called.

import { truncate } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
truncate('path/file.txt', (err) => {
  if (err) throw err;
  console.log('path/file.txt was truncated');
});

Passing a file descriptor is deprecated and may result in an error being thrown in the future.

See the POSIX truncate(2) documentation for more details.

Parameters

path: PathLike
len: number | undefined = 0
optional
callback: NoParamCallback

Return Type

void

Overload 2

truncate(
path: PathLike,
callback: NoParamCallback,
): void

Asynchronous truncate(2) - Truncate a file to a specified length.

Parameters

path: PathLike

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

callback: NoParamCallback

Return Type

void

function truncateSync

Usage in Deno

import { truncateSync } from "node:fs";
truncateSync(
path: PathLike,
len?: number,
): void

Truncates the file. Returns undefined. A file descriptor can also be passed as the first argument. In this case, fs.ftruncateSync() is called.

Passing a file descriptor is deprecated and may result in an error being thrown in the future.

Parameters

path: PathLike
len: number = 0
optional

Return Type

void

function unlink

Usage in Deno

import { unlink } from "node:fs";
unlink(
path: PathLike,
callback: NoParamCallback,
): void

Asynchronously removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback.

import { unlink } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
unlink('path/file.txt', (err) => {
  if (err) throw err;
  console.log('path/file.txt was deleted');
});

fs.unlink() will not work on a directory, empty or otherwise. To remove a directory, use rmdir.

See the POSIX unlink(2) documentation for more details.

Parameters

path: PathLike
callback: NoParamCallback

Return Type

void

function unlinkSync

Usage in Deno

import { unlinkSync } from "node:fs";
unlinkSync(path: PathLike): void

Synchronous unlink(2). Returns undefined.

Parameters

path: PathLike

Return Type

void

function unwatchFile

Usage in Deno

import { unwatchFile } from "node:fs";

Overload 1

unwatchFile(
filename: PathLike,
listener?: StatsListener,
): void

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 fs.unwatchFile() with a filename that is not being watched is a no-op, not an error.

Using watch is more efficient than fs.watchFile() and fs.unwatchFile(). fs.watch() should be used instead of fs.watchFile() and fs.unwatchFile() when possible.

Parameters

filename: PathLike
listener: StatsListener
optional

Optional, a listener previously attached using fs.watchFile()

Return Type

void

Overload 2

unwatchFile(
filename: PathLike,
listener?: BigIntStatsListener,
): void

Parameters

filename: PathLike
listener: BigIntStatsListener
optional

Return Type

void

function utimes

Usage in Deno

import { utimes } from "node:fs";
utimes(
path: PathLike,
atime: TimeLike,
mtime: TimeLike,
callback: NoParamCallback,
): void

Change the file system timestamps of the object referenced by path.

The atime and mtime arguments follow these rules:

  • Values can be either numbers representing Unix epoch time in seconds, Dates, or a numeric string like '123456789.0'.
  • If the value can not be converted to a number, or is NaN, Infinity, or -Infinity, an Error will be thrown.

Parameters

path: PathLike
atime: TimeLike
mtime: TimeLike
callback: NoParamCallback

Return Type

void

function utimesSync

Usage in Deno

import { utimesSync } from "node:fs";
utimesSync(
path: PathLike,
atime: TimeLike,
mtime: TimeLike,
): void

Returns undefined.

For detailed information, see the documentation of the asynchronous version of this API: utimes.

Parameters

path: PathLike
atime: TimeLike
mtime: TimeLike

Return Type

void

function watch

Usage in Deno

import { watch } from "node:fs";

Overload 1

watch(
filename: PathLike,
options: (WatchOptions & { encoding: "buffer"; }) | "buffer",
listener?: WatchListener<Buffer>,
): FSWatcher

Watch for changes on filename, where filename is 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). eventTypeis 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 of eventType.

If a signal is passed, aborting the corresponding AbortController will close the returned fs.FSWatcher.

Parameters

filename: PathLike
options: (WatchOptions & { encoding: "buffer"; }) | "buffer"
listener: WatchListener<Buffer>
optional

Return Type

FSWatcher

Overload 2

watch(
filename: PathLike,
options?:
WatchOptions
| BufferEncoding
| null
,
listener?: WatchListener<string>,
): FSWatcher

Watch for changes on filename, where filename is either a file or a directory, returning an FSWatcher.

Parameters

filename: PathLike

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

options:
WatchOptions
| BufferEncoding
| null
optional

Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. If encoding is not supplied, the default of 'utf8' is used. If persistent is not supplied, the default of true is used. If recursive is not supplied, the default of false is used.

listener: WatchListener<string>
optional

Return Type

FSWatcher

Overload 3

watch(
filename: PathLike,
options: WatchOptions | string,
listener?: WatchListener<string | Buffer>,
): FSWatcher

Watch for changes on filename, where filename is either a file or a directory, returning an FSWatcher.

Parameters

filename: PathLike

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

options: WatchOptions | string

Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. If encoding is not supplied, the default of 'utf8' is used. If persistent is not supplied, the default of true is used. If recursive is not supplied, the default of false is used.

listener: WatchListener<string | Buffer>
optional

Return Type

FSWatcher

Overload 4

watch(
filename: PathLike,
listener?: WatchListener<string>,
): FSWatcher

Watch for changes on filename, where filename is either a file or a directory, returning an FSWatcher.

Parameters

filename: PathLike

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

listener: WatchListener<string>
optional

Return Type

FSWatcher

function watchFile

Usage in Deno

import { watchFile } from "node:fs";

Overload 1

watchFile(
filename: PathLike,
options: (WatchFileOptions & { bigint?: false | undefined; }) | undefined,
listener: StatsListener,
): StatWatcher

Watch for changes on filename. The callback listener will be called each time the file is accessed.

The options argument may be omitted. If provided, it should be an object. The options object may contain a boolean named persistent that indicates whether the process should continue to run as long as files are being watched. The options object may specify an interval property indicating how often the target should be polled in milliseconds.

The listener gets two arguments the current stat object and the previous stat object:

import { watchFile } from 'node:fs';

watchFile('message.text', (curr, prev) => {
  console.log(`the current mtime is: ${curr.mtime}`);
  console.log(`the previous mtime was: ${prev.mtime}`);
});

These stat objects are instances of fs.Stat. If the bigint option is true, the numeric values in these objects are specified as BigInts.

To be notified when the file was modified, not just accessed, it is necessary to compare curr.mtimeMs and prev.mtimeMs.

When an fs.watchFile operation results in an ENOENT error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.

Using watch is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.

When a file being watched by fs.watchFile() disappears and reappears, then the contents of previous in the second callback event (the file's reappearance) will be the same as the contents of previous in the first callback event (its disappearance).

This happens when:

  • the file is deleted, followed by a restore
  • the file is renamed and then renamed a second time back to its original name

Parameters

filename: PathLike
options: (WatchFileOptions & { bigint?: false | undefined; }) | undefined
listener: StatsListener

Return Type

StatWatcher

Overload 2

watchFile(
filename: PathLike,
options: (WatchFileOptions & { bigint: true; }) | undefined,
listener: BigIntStatsListener,
): StatWatcher

Parameters

filename: PathLike
options: (WatchFileOptions & { bigint: true; }) | undefined
listener: BigIntStatsListener

Return Type

StatWatcher

Overload 3

watchFile(
filename: PathLike,
listener: StatsListener,
): StatWatcher

Watch for changes on filename. The callback listener will be called each time the file is accessed.

Parameters

filename: PathLike

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

listener: StatsListener

Return Type

StatWatcher

function write

Usage in Deno

import { write } from "node:fs";

Overload 1

write<TBuffer extends ArrayBufferView>(
fd: number,
buffer: TBuffer,
offset:
number
| undefined
| null
,
length:
number
| undefined
| null
,
position:
number
| undefined
| null
,
callback: (
err: ErrnoException | null,
written: number,
buffer: TBuffer,
) => void
,
): void

Write buffer to the file specified by fd.

offset determines the part of the buffer to be written, and length is an integer specifying the number of bytes to write.

position refers to the offset from the beginning of the file where this data should be written. If typeof position !== 'number', the data will be written at the current position. See pwrite(2).

The callback will be given three arguments (err, bytesWritten, buffer) where bytesWritten specifies how many bytes were written from buffer.

If this method is invoked as its util.promisify() ed version, it returns a promise for an Object with bytesWritten and buffer properties.

It is unsafe to use fs.write() multiple times on the same file without waiting for the callback. For this scenario, createWriteStream is recommended.

On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.

Type Parameters

TBuffer extends ArrayBufferView

Parameters

fd: number
buffer: TBuffer
offset:
number
| undefined
| null
= 0
optional
length:
number
| undefined
| null
= buffer.byteLength - offset
optional
position:
number
| undefined
| null
= 'null'
optional
callback: (
err: ErrnoException | null,
written: number,
buffer: TBuffer,
) => void

Return Type

void

Overload 2

write<TBuffer extends ArrayBufferView>(
fd: number,
buffer: TBuffer,
offset:
number
| undefined
| null
,
length:
number
| undefined
| null
,
callback: (
err: ErrnoException | null,
written: number,
buffer: TBuffer,
) => void
,
): void

Asynchronously writes buffer to the file referenced by the supplied file descriptor.

Type Parameters

TBuffer extends ArrayBufferView

Parameters

fd: number

A file descriptor.

buffer: TBuffer
offset:
number
| undefined
| null

The part of the buffer to be written. If not supplied, defaults to 0.

length:
number
| undefined
| null

The number of bytes to write. If not supplied, defaults to buffer.length - offset.

callback: (
err: ErrnoException | null,
written: number,
buffer: TBuffer,
) => void

Return Type

void

Overload 3

write<TBuffer extends ArrayBufferView>(
fd: number,
buffer: TBuffer,
offset:
number
| undefined
| null
,
callback: (
err: ErrnoException | null,
written: number,
buffer: TBuffer,
) => void
,
): void

Asynchronously writes buffer to the file referenced by the supplied file descriptor.

Type Parameters

TBuffer extends ArrayBufferView

Parameters

fd: number

A file descriptor.

buffer: TBuffer
offset:
number
| undefined
| null

The part of the buffer to be written. If not supplied, defaults to 0.

callback: (
err: ErrnoException | null,
written: number,
buffer: TBuffer,
) => void

Return Type

void

Overload 4

write<TBuffer extends ArrayBufferView>(
fd: number,
buffer: TBuffer,
callback: (
err: ErrnoException | null,
written: number,
buffer: TBuffer,
) => void
,
): void

Asynchronously writes buffer to the file referenced by the supplied file descriptor.

Type Parameters

TBuffer extends ArrayBufferView

Parameters

fd: number

A file descriptor.

buffer: TBuffer
callback: (
err: ErrnoException | null,
written: number,
buffer: TBuffer,
) => void

Return Type

void

Overload 5

write(
fd: number,
string: string,
position:
number
| undefined
| null
,
encoding:
BufferEncoding
| undefined
| null
,
callback: (
err: ErrnoException | null,
written: number,
str: string,
) => void
,
): void

Asynchronously writes string to the file referenced by the supplied file descriptor.

Parameters

fd: number

A file descriptor.

string: string

A string to write.

position:
number
| undefined
| null

The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.

encoding:
BufferEncoding
| undefined
| null

The expected string encoding.

callback: (
err: ErrnoException | null,
written: number,
str: string,
) => void

Return Type

void

Overload 6

write(
fd: number,
string: string,
position:
number
| undefined
| null
,
callback: (
err: ErrnoException | null,
written: number,
str: string,
) => void
,
): void

Asynchronously writes string to the file referenced by the supplied file descriptor.

Parameters

fd: number

A file descriptor.

string: string

A string to write.

position:
number
| undefined
| null

The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.

callback: (
err: ErrnoException | null,
written: number,
str: string,
) => void

Return Type

void

Overload 7

write(
fd: number,
string: string,
callback: (
err: ErrnoException | null,
written: number,
str: string,
) => void
,
): void

Asynchronously writes string to the file referenced by the supplied file descriptor.

Parameters

fd: number

A file descriptor.

string: string

A string to write.

callback: (
err: ErrnoException | null,
written: number,
str: string,
) => void

Return Type

void

function writeFile

Usage in Deno

import { writeFile } from "node:fs";

Overload 1

writeFile(
file: PathOrFileDescriptor,
data: string | ArrayBufferView,
options: WriteFileOptions,
callback: NoParamCallback,
): void
Deno compatibility

Missing utf16le, latin1 and ucs2 encoding.

When file is a filename, asynchronously writes data to the file, replacing the file if it already exists. data can be a string or a buffer.

When file is a file descriptor, the behavior is similar to calling fs.write() directly (which is recommended). See the notes below on using a file descriptor.

The encoding option is ignored if data is a buffer.

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

import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';

const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
});

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

import { writeFile } from 'node:fs';

writeFile('message.txt', 'Hello Node.js', 'utf8', callback);

It is unsafe to use fs.writeFile() multiple times on the same file without waiting for the callback. For this scenario, createWriteStream is recommended.

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

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

import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';

const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, { signal }, (err) => {
  // When a request is aborted - the callback is called with an AbortError
});
// When the request should be aborted
controller.abort();

Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.writeFile performs.

Parameters

file: PathOrFileDescriptor

filename or file descriptor

data: string | ArrayBufferView
options: WriteFileOptions
callback: NoParamCallback

Return Type

void

Overload 2

writeFile(
path: PathOrFileDescriptor,
data: string | ArrayBufferView,
callback: NoParamCallback,
): void
Deno compatibility

Missing utf16le, latin1 and ucs2 encoding.

Asynchronously writes data to a file, replacing the file if it already exists.

Parameters

path: PathOrFileDescriptor

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

data: string | ArrayBufferView

The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.

callback: NoParamCallback

Return Type

void

function writeFileSync

Usage in Deno

import { writeFileSync } from "node:fs";
writeFileSync(
file: PathOrFileDescriptor,
data: string | ArrayBufferView,
options?: WriteFileOptions,
): void
Deno compatibility

Missing utf16le, latin1 and ucs2 encoding.

Returns undefined.

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

For detailed information, see the documentation of the asynchronous version of this API: writeFile.

Parameters

file: PathOrFileDescriptor

filename or file descriptor

data: string | ArrayBufferView
options: WriteFileOptions
optional

Return Type

void

function writeSync

Usage in Deno

import { writeSync } from "node:fs";

Overload 1

writeSync(
fd: number,
buffer: ArrayBufferView,
offset?: number | null,
length?: number | null,
position?: number | null,
): number

For detailed information, see the documentation of the asynchronous version of this API: write.

Parameters

fd: number
buffer: ArrayBufferView
offset: number | null = 0
optional
length: number | null = buffer.byteLength - offset
optional
position: number | null = 'null'
optional

Return Type

number

The number of bytes written.

Overload 2

writeSync(
fd: number,
string: string,
position?: number | null,
encoding?: BufferEncoding | null,
): number

Synchronously writes string to the file referenced by the supplied file descriptor, returning the number of bytes written.

Parameters

fd: number

A file descriptor.

string: string

A string to write.

position: number | null
optional

The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.

encoding: BufferEncoding | null
optional

The expected string encoding.

Return Type

number

function writev

Usage in Deno

import { writev } from "node:fs";

Overload 1

writev(
fd: number,
buffers: readonly ArrayBufferView[],
cb: (
err: ErrnoException | null,
bytesWritten: number,
buffers: ArrayBufferView[],
) => void
,
): void

Write an array of ArrayBufferViews to the file specified by fd using writev().

position is the offset from the beginning of the file where this data should be written. If typeof position !== 'number', the data will be written at the current position.

The callback will be given three arguments: err, bytesWritten, and buffers. bytesWritten is how many bytes were written from buffers.

If this method is util.promisify() ed, it returns a promise for an Object with bytesWritten and buffers properties.

It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use createWriteStream.

On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.

Parameters

fd: number
buffers: readonly ArrayBufferView[]
cb: (
err: ErrnoException | null,
bytesWritten: number,
buffers: ArrayBufferView[],
) => void

Return Type

void

Overload 2

writev(
fd: number,
buffers: readonly ArrayBufferView[],
position: number | null,
cb: (
err: ErrnoException | null,
bytesWritten: number,
buffers: ArrayBufferView[],
) => void
,
): void

Parameters

fd: number
buffers: readonly ArrayBufferView[]
position: number | null
cb: (
err: ErrnoException | null,
bytesWritten: number,
buffers: ArrayBufferView[],
) => void

Return Type

void

function writevSync

Usage in Deno

import { writevSync } from "node:fs";
writevSync(
fd: number,
buffers: readonly ArrayBufferView[],
position?: number,
): number

For detailed information, see the documentation of the asynchronous version of this API: writev.

Parameters

fd: number
buffers: readonly ArrayBufferView[]
position: number = 'null'
optional

Return Type

number

The number of bytes written.


function exists

Usage in Deno

import { exists } from "node:fs";
exists(
path: PathLike,
callback: (exists: boolean) => void,
): void
Deprecated

Test whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false:

import { exists } from 'node:fs';

exists('/etc/passwd', (e) => {
  console.log(e ? 'it exists' : 'no passwd!');
});

The parameters for this callback are not consistent with other Node.js callbacks. Normally, the first parameter to a Node.js callback is an err parameter, optionally followed by other parameters. The fs.exists() callback has only one boolean parameter. This is one reason fs.access() is recommended instead of fs.exists().

Using fs.exists() to check for the existence of a file before calling fs.open(), fs.readFile(), or fs.writeFile() 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 does not exist.

write (NOT RECOMMENDED)

import { exists, open, close } from 'node:fs';

exists('myfile', (e) => {
  if (e) {
    console.error('myfile already exists');
  } else {
    open('myfile', 'wx', (err, fd) => {
      if (err) throw err;

      try {
        writeMyData(fd);
      } finally {
        close(fd, (err) => {
          if (err) throw err;
        });
      }
    });
  }
});

write (RECOMMENDED)

import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
  if (err) {
    if (err.code === 'EEXIST') {
      console.error('myfile already exists');
      return;
    }

    throw err;
  }

  try {
    writeMyData(fd);
  } finally {
    close(fd, (err) => {
      if (err) throw err;
    });
  }
});

read (NOT RECOMMENDED)

import { open, close, exists } from 'node:fs';

exists('myfile', (e) => {
  if (e) {
    open('myfile', 'r', (err, fd) => {
      if (err) throw err;

      try {
        readMyData(fd);
      } finally {
        close(fd, (err) => {
          if (err) throw err;
        });
      }
    });
  } else {
    console.error('myfile does not exist');
  }
});

read (RECOMMENDED)

import { open, close } from 'node:fs';

open('myfile', 'r', (err, fd) => {
  if (err) {
    if (err.code === 'ENOENT') {
      console.error('myfile does not exist');
      return;
    }

    throw err;
  }

  try {
    readMyData(fd);
  } finally {
    close(fd, (err) => {
      if (err) throw err;
    });
  }
});

The "not recommended" examples above check for existence and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.

In general, check for the existence of a file only if the file won't be used directly, for example when its existence is a signal from another process.

Parameters

path: PathLike
callback: (exists: boolean) => void

Return Type

void

function lchmod

Usage in Deno

import { lchmod } from "node:fs";
lchmod(
path: PathLike,
mode: Mode,
callback: NoParamCallback,
): void
Deprecated

Changes the permissions on a symbolic link. No arguments other than a possible exception are given to the completion callback.

This method is only implemented on macOS.

See the POSIX lchmod(2) documentation for more detail.

Parameters

path: PathLike
mode: Mode
callback: NoParamCallback

Return Type

void

function lchmodSync

Usage in Deno

import { lchmodSync } from "node:fs";
lchmodSync(
path: PathLike,
mode: Mode,
): void
Deprecated

Changes the permissions on a symbolic link. Returns undefined.

This method is only implemented on macOS.

See the POSIX lchmod(2) documentation for more detail.

Parameters

path: PathLike
mode: Mode

Return Type

void

function promises.lchmod

Usage in Deno

import { promises } from "node:fs";
const { lchmod } = promises;
lchmod(
path: PathLike,
mode: Mode,
): Promise<void>
Deprecated
Deno compatibility

The lchmod implementation is a not implemented.

Changes the permissions on a symbolic link.

This method is only implemented on macOS.

Parameters

path: PathLike
mode: Mode

Return Type

Promise<void>

Fulfills with undefined upon success.


interface _GlobOptions

Usage in Deno

import { type _GlobOptions } from "node:fs";

Type Parameters

T extends Dirent | string

Properties

cwd: string | undefined
optional

Current working directory.

withFileTypes: boolean | undefined
optional

true if the glob should return paths as Dirents, false otherwise.

exclude:
((fileName: T) => boolean)
| readonly string[]
| undefined
optional

Function to filter out files/directories or a list of glob patterns to be excluded. If a function is provided, return true to exclude the item, false to include it.


interface BigIntOptions

Usage in Deno

import { type BigIntOptions } from "node:fs";

Properties

bigint: true

interface BigIntStats

extends StatsBase<bigint>

Usage in Deno

import { type BigIntStats } from "node:fs";

Properties

atimeNs: bigint
mtimeNs: bigint
ctimeNs: bigint
birthtimeNs: bigint

interface BigIntStatsFs

extends StatsFsBase<bigint>

Usage in Deno

import { type BigIntStatsFs } from "node:fs";

interface CopyOptions

extends CopyOptionsBase

Usage in Deno

import { type CopyOptions } from "node:fs";

Methods

filter(
source: string,
destination: string,
): boolean | Promise<boolean>
optional

Function to filter copied files/directories. Return true to copy the item, false to ignore it.


interface CopyOptionsBase

Usage in Deno

import { type CopyOptionsBase } from "node:fs";

Properties

dereference: boolean
optional

Dereference symlinks

errorOnExist: boolean
optional

When force is false, and the destination exists, throw an error.

force: boolean
optional

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.

mode: number
optional

Modifiers for copy operation. See mode flag of copyFileSync()

preserveTimestamps: boolean
optional

When true timestamps from src will be preserved.

recursive: boolean
optional

Copy directories recursively.

verbatimSymlinks: boolean
optional

When true, path resolution for symlinks will be skipped


interface CopySyncOptions

extends CopyOptionsBase

Usage in Deno

import { type CopySyncOptions } from "node:fs";

Methods

filter(
source: string,
destination: string,
): boolean
optional

Function to filter copied files/directories. Return true to copy the item, false to ignore it.


interface CreateReadStreamFSImplementation

extends FSImplementation

Usage in Deno

import { type CreateReadStreamFSImplementation } from "node:fs";

Properties

read: (...args: any[]) => any

interface CreateWriteStreamFSImplementation

extends FSImplementation

Usage in Deno

import { type CreateWriteStreamFSImplementation } from "node:fs";

Properties

write: (...args: any[]) => any
writev: (...args: any[]) => any
optional

interface FSImplementation

Usage in Deno

import { type FSImplementation } from "node:fs";

Properties

open: (...args: any[]) => any
optional
close: (...args: any[]) => any
optional

interface FSWatcher

extends EventEmitter

Usage in Deno

import { type FSWatcher } from "node:fs";

Methods

close(): void

Stop watching for changes on the given fs.FSWatcher. Once stopped, the fs.FSWatcher object is no longer usable.

ref(): this

When called, requests that the Node.js event loop not exit so long as the fs.FSWatcher is active. Calling watcher.ref() multiple times will have no effect.

By default, all fs.FSWatcher objects are "ref'ed", making it normally unnecessary to call watcher.ref() unless watcher.unref() had been called previously.

unref(): this

When called, the active fs.FSWatcher object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the fs.FSWatcher object's callback is invoked. Calling watcher.unref() multiple times will have no effect.

addListener(
event: string,
listener: (...args: any[]) => void,
): this

events.EventEmitter

  1. change
  2. close
  3. error
addListener(
event: "change",
listener: (
eventType: string,
filename: string | Buffer,
) => void
,
): this
addListener(
event: "close",
listener: () => void,
): this
addListener(
event: "error",
listener: (error: Error) => void,
): this
on(
event: string,
listener: (...args: any[]) => void,
): this
on(
event: "change",
listener: (
eventType: string,
filename: string | Buffer,
) => void
,
): this
on(
event: "close",
listener: () => void,
): this
on(
event: "error",
listener: (error: Error) => void,
): this
once(
event: string,
listener: (...args: any[]) => void,
): this
once(
event: "change",
listener: (
eventType: string,
filename: string | Buffer,
) => void
,
): this
once(
event: "close",
listener: () => void,
): this
once(
event: "error",
listener: (error: Error) => void,
): this
prependListener(
event: string,
listener: (...args: any[]) => void,
): this
prependListener(
event: "change",
listener: (
eventType: string,
filename: string | Buffer,
) => void
,
): this
prependListener(
event: "close",
listener: () => void,
): this
prependListener(
event: "error",
listener: (error: Error) => void,
): this
prependOnceListener(
event: string,
listener: (...args: any[]) => void,
): this
prependOnceListener(
event: "change",
listener: (
eventType: string,
filename: string | Buffer,
) => void
,
): this
prependOnceListener(
event: "close",
listener: () => void,
): this
prependOnceListener(
event: "error",
listener: (error: Error) => void,
): this

interface GlobOptions

extends _GlobOptions<Dirent | string>

Usage in Deno

import { type GlobOptions } from "node:fs";

interface GlobOptionsWithFileTypes

extends _GlobOptions<Dirent>

Usage in Deno

import { type GlobOptionsWithFileTypes } from "node:fs";

Properties

withFileTypes: true

interface GlobOptionsWithoutFileTypes

extends _GlobOptions<string>

Usage in Deno

import { type GlobOptionsWithoutFileTypes } from "node:fs";

Properties

withFileTypes: false | undefined
optional

interface MakeDirectoryOptions

Usage in Deno

import { type MakeDirectoryOptions } from "node:fs";

Properties

recursive: boolean | undefined
optional

Indicates whether parent folders should be created. If a folder was created, the path to the first created folder will be returned.

mode: Mode | undefined
optional

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


interface ObjectEncodingOptions

Usage in Deno

import { type ObjectEncodingOptions } from "node:fs";

Properties

encoding:
BufferEncoding
| null
| undefined
optional

interface OpenAsBlobOptions

Usage in Deno

import { type OpenAsBlobOptions } from "node:fs";

Properties

type: string | undefined
optional

An optional mime type for the blob.


interface OpenDirOptions

Usage in Deno

import { type OpenDirOptions } from "node:fs";

Properties

encoding: BufferEncoding | undefined
optional
bufferSize: number | undefined
optional

Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage.

recursive: boolean
optional

interface promises.CreateReadStreamOptions

extends Abortable

Usage in Deno

import { type promises } from "node:fs";
type { CreateReadStreamOptions } = promises;

Properties

encoding:
BufferEncoding
| null
| undefined
optional
autoClose: boolean | undefined
optional
emitClose: boolean | undefined
optional
start: number | undefined
optional
end: number | undefined
optional
highWaterMark: number | undefined
optional

interface promises.CreateWriteStreamOptions

Usage in Deno

import { type promises } from "node:fs";
type { CreateWriteStreamOptions } = promises;

Properties

encoding:
BufferEncoding
| null
| undefined
optional
autoClose: boolean | undefined
optional
emitClose: boolean | undefined
optional
start: number | undefined
optional
highWaterMark: number | undefined
optional
flush: boolean | undefined
optional

interface promises.FileChangeInfo

Usage in Deno

import { type promises } from "node:fs";
type { FileChangeInfo } = promises;

Type Parameters

T extends string | Buffer

Properties

eventType: WatchEventType
filename: T | null

interface promises.FileHandle

Usage in Deno

import { type promises } from "node:fs";
type { FileHandle } = promises;

Properties

fd: number
readonly

The numeric file descriptor managed by the {FileHandle} object.

Methods

appendFile(
data: string | Uint8Array,
options?:
(ObjectEncodingOptions & Abortable)
| BufferEncoding
| null
,
): Promise<void>

Alias of filehandle.writeFile().

When operating on file handles, the mode cannot be changed from what it was set to with fsPromises.open(). Therefore, this is equivalent to filehandle.writeFile().

chown(
uid: number,
gid: number,
): Promise<void>

Changes the ownership of the file. A wrapper for chown(2).

chmod(mode: Mode): Promise<void>

Modifies the permissions on the file. See chmod(2).

createReadStream(options?: CreateReadStreamOptions): ReadStream

Unlike the 16 KiB default highWaterMark for a stream.Readable, the stream returned by this method has a default highWaterMark of 64 KiB.

options can include start and end values to read a range of bytes from the file instead of the entire file. Both start and end are inclusive and start counting at 0, allowed values are in the [0, Number.MAX_SAFE_INTEGER] range. If start is omitted or undefined, filehandle.createReadStream() reads sequentially from the current file position. The encoding can be any one of those accepted by Buffer.

If the FileHandle points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally.

By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.

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

const fd = await open('/dev/input/event0');
// Create a stream from some character device.
const stream = fd.createReadStream();
setTimeout(() => {
  stream.close(); // This may not close the stream.
  // Artificially marking end-of-stream, as if the underlying resource had
  // indicated end-of-file by itself, allows the stream to close.
  // This does not cancel pending read operations, and if there is such an
  // operation, the process may still not be able to exit successfully
  // until it finishes.
  stream.push(null);
  stream.read(0);
}, 100);

If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. If autoClose is set to true (default behavior), on 'error' or 'end' the file descriptor will be closed automatically.

An example to read the last 10 bytes of a file which is 100 bytes long:

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

const fd = await open('sample.txt');
fd.createReadStream({ start: 90, end: 99 });
createWriteStream(options?: CreateWriteStreamOptions): WriteStream

options may also include a start option to allow writing data at some position past the beginning of the file, allowed values are in the [0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather than replacing it may require the flags open option to be set to r+ rather than the default r. The encoding can be any one of those accepted by Buffer.

If autoClose is set to true (default behavior) on 'error' or 'finish' the file descriptor will be closed automatically. If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.

By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.

datasync(): Promise<void>

Forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details.

Unlike filehandle.sync this method does not flush modified metadata.

sync(): Promise<void>

Request that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail.

read<T extends ArrayBufferView>(
buffer: T,
offset?: number | null,
length?: number | null,
position?: number | null,
): Promise<FileReadResult<T>>

Reads data from the file and stores that in the given buffer.

If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.

read<T extends ArrayBufferView = Buffer>(
buffer: T,
options?: FileReadOptions<T>,
): Promise<FileReadResult<T>>
read<T extends ArrayBufferView = Buffer>(options?: FileReadOptions<T>): Promise<FileReadResult<T>>
readableWebStream(options?: ReadableWebStreamOptions): ReadableStream

Returns a ReadableStream that may be used to read the files data.

An error will be thrown if this method is called more than once or is called after the FileHandle is closed or closing.

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

const file = await open('./some/file/to/read');

for await (const chunk of file.readableWebStream())
  console.log(chunk);

await file.close();

While the ReadableStream will read the file to completion, it will not close the FileHandle automatically. User code must still call thefileHandle.close() method.

readFile(options?: { encoding?: null | undefined; flag?: OpenMode | undefined; } | null): Promise<Buffer>

Asynchronously reads the entire contents of a file.

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

The FileHandle has to support reading.

If one or more filehandle.read() calls are made on a file handle and then a filehandle.readFile() call is made, the data will be read from the current position till the end of the file. It doesn't always read from the beginning of the file.

readFile(options: { encoding: BufferEncoding; flag?: OpenMode | undefined; } | BufferEncoding): Promise<string>

Asynchronously reads the entire contents of a file. The underlying file will not be closed automatically. The FileHandle must have been opened for reading.

readFile(options?:
(ObjectEncodingOptions & { flag?: OpenMode | undefined; })
| BufferEncoding
| null
): Promise<string | Buffer>

Asynchronously reads the entire contents of a file. The underlying file will not be closed automatically. The FileHandle must have been opened for reading.

readLines(options?: CreateReadStreamOptions): ReadlineInterface

Convenience method to create a readline interface and stream over the file. See filehandle.createReadStream() for the options.

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

const file = await open('./some/file/to/read');

for await (const line of file.readLines()) {
  console.log(line);
}
stat(opts?: StatOptions & { bigint?: false | undefined; }): Promise<Stats>
stat(opts: StatOptions & { bigint: true; }): Promise<BigIntStats>
stat(opts?: StatOptions): Promise<Stats | BigIntStats>
truncate(len?: number): Promise<void>

Truncates the file.

If the file was larger than len bytes, only the first len bytes will be retained in the file.

The following example retains only the first four bytes of the file:

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

let filehandle = null;
try {
  filehandle = await open('temp.txt', 'r+');
  await filehandle.truncate(4);
} finally {
  await filehandle?.close();
}

If the file previously was shorter than len bytes, it is extended, and the extended part is filled with null bytes ('\0'):

If len is negative then 0 will be used.

utimes(
atime: TimeLike,
mtime: TimeLike,
): Promise<void>

Change the file system timestamps of the object referenced by the FileHandle then fulfills the promise with no arguments upon success.

writeFile(
data: string | Uint8Array,
options?:
(ObjectEncodingOptions & Abortable)
| BufferEncoding
| null
,
): 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 promise is fulfilled with no arguments upon success.

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

The FileHandle has to support writing.

It is unsafe to use filehandle.writeFile() multiple times on the same file without waiting for the promise to be fulfilled (or rejected).

If one or more filehandle.write() calls are made on a file handle and then afilehandle.writeFile() call is made, the data will be written from the current position till the end of the file. It doesn't always write from the beginning of the file.

write<TBuffer extends Uint8Array>(
buffer: TBuffer,
offset?: number | null,
length?: number | null,
position?: number | null,
): Promise<{ bytesWritten: number; buffer: TBuffer; }>

Write buffer to the file.

The promise is fulfilled with an object containing two properties:

It is unsafe to use filehandle.write() multiple times on the same file without waiting for the promise to be fulfilled (or rejected). For this scenario, use filehandle.createWriteStream().

On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.

write<TBuffer extends Uint8Array>(
buffer: TBuffer,
options?: { offset?: number; length?: number; position?: number; },
): Promise<{ bytesWritten: number; buffer: TBuffer; }>
write(
data: string,
position?: number | null,
encoding?: BufferEncoding | null,
): Promise<{ bytesWritten: number; buffer: string; }>
writev(
buffers: readonly ArrayBufferView[],
position?: number,
): Promise<WriteVResult>

Write an array of ArrayBufferView s to the file.

The promise is fulfilled with an object containing a two properties:

It is unsafe to call writev() multiple times on the same file without waiting for the promise to be fulfilled (or rejected).

On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.

readv(
buffers: readonly ArrayBufferView[],
position?: number,
): Promise<ReadVResult>

Read from a file and write to an array of ArrayBufferView s

close(): Promise<void>

Closes the file handle after waiting for any pending operation on the handle to complete.

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

let filehandle;
try {
  filehandle = await open('thefile.txt', 'r');
} finally {
  await filehandle?.close();
}
[[Symbol.asyncDispose]](): Promise<void>

An alias for FileHandle.close().


interface promises.FileReadOptions

Usage in Deno

import { type promises } from "node:fs";
type { FileReadOptions } = promises;

Type Parameters

T extends ArrayBufferView = Buffer

Properties

buffer: T
optional
offset: number | null
optional
length: number | null
optional
position: number | null
optional

interface promises.FileReadResult

Usage in Deno

import { type promises } from "node:fs";
type { FileReadResult } = promises;

Type Parameters

T extends ArrayBufferView

Properties

bytesRead: number
buffer: T

interface promises.FlagAndOpenMode

Usage in Deno

import { type promises } from "node:fs";
type { FlagAndOpenMode } = promises;

Properties

mode: Mode | undefined
optional
flag: OpenMode | undefined
optional

interface promises.ReadableWebStreamOptions

Usage in Deno

import { type promises } from "node:fs";
type { ReadableWebStreamOptions } = promises;

Properties

type: "bytes" | undefined
optional

Whether to open a normal or a 'bytes' stream.


interface ReadAsyncOptions

extends ReadSyncOptions

Usage in Deno

import { type ReadAsyncOptions } from "node:fs";

Type Parameters

TBuffer extends ArrayBufferView

Properties

buffer: TBuffer
optional

interface ReadStreamOptions

extends StreamOptions

Usage in Deno

import { type ReadStreamOptions } from "node:fs";

Properties

fs:
CreateReadStreamFSImplementation
| null
| undefined
optional
end: number | undefined
optional

interface ReadSyncOptions

Usage in Deno

import { type ReadSyncOptions } from "node:fs";

Properties

offset: number | undefined
optional
length: number | undefined
optional
position:
ReadPosition
| null
| undefined
optional

interface ReadVResult

Usage in Deno

import { type ReadVResult } from "node:fs";

Properties

bytesRead: number
buffers: ArrayBufferView[]

interface RmDirOptions

Usage in Deno

import { type RmDirOptions } from "node:fs";

Properties

maxRetries: number | undefined
optional

If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or EPERM error is encountered, Node.js will retry the operation with a linear backoff wait of retryDelay ms longer on each try. This option represents the number of retries. This option is ignored if the recursive option is not true.

recursive: boolean | undefined
deprecated
optional
retryDelay: number | undefined
optional

The amount of time in milliseconds to wait between retries. This option is ignored if the recursive option is not true.


interface RmOptions

Usage in Deno

import { type RmOptions } from "node:fs";

Properties

force: boolean | undefined
optional

When true, exceptions will be ignored if path does not exist.

maxRetries: number | undefined
optional

If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or EPERM error is encountered, Node.js will retry the operation with a linear backoff wait of retryDelay ms longer on each try. This option represents the number of retries. This option is ignored if the recursive option is not true.

recursive: boolean | undefined
optional

If true, perform a recursive directory removal. In recursive mode, operations are retried on failure.

retryDelay: number | undefined
optional

The amount of time in milliseconds to wait between retries. This option is ignored if the recursive option is not true.


interface StatFsOptions

Usage in Deno

import { type StatFsOptions } from "node:fs";

Properties

bigint: boolean | undefined
optional

interface StatOptions

Usage in Deno

import { type StatOptions } from "node:fs";

Properties

bigint: boolean | undefined
optional

class Stats

Usage in Deno

import { Stats } from "node:fs";

A fs.Stats object provides information about a file.

Objects returned from stat, lstat, fstat, and their synchronous counterparts are of this type. If bigint in the options passed to those methods is true, the numeric values will be bigint instead of number, and the object will contain additional nanosecond-precision properties suffixed with Ns. Stat objects are not to be created directly using the new keyword.

Stats {
  dev: 2114,
  ino: 48064969,
  mode: 33188,
  nlink: 1,
  uid: 85,
  gid: 100,
  rdev: 0,
  size: 527,
  blksize: 4096,
  blocks: 8,
  atimeMs: 1318289051000.1,
  mtimeMs: 1318289051000.1,
  ctimeMs: 1318289051000.1,
  birthtimeMs: 1318289051000.1,
  atime: Mon, 10 Oct 2011 23:24:11 GMT,
  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }

bigint version:

BigIntStats {
  dev: 2114n,
  ino: 48064969n,
  mode: 33188n,
  nlink: 1n,
  uid: 85n,
  gid: 100n,
  rdev: 0n,
  size: 527n,
  blksize: 4096n,
  blocks: 8n,
  atimeMs: 1318289051000n,
  mtimeMs: 1318289051000n,
  ctimeMs: 1318289051000n,
  birthtimeMs: 1318289051000n,
  atimeNs: 1318289051000000000n,
  mtimeNs: 1318289051000000000n,
  ctimeNs: 1318289051000000000n,
  birthtimeNs: 1318289051000000000n,
  atime: Mon, 10 Oct 2011 23:24:11 GMT,
  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }

Constructors

Stats()
new

interface Stats

extends StatsBase<number>

interface StatsBase

Usage in Deno

import { type StatsBase } from "node:fs";

Type Parameters

T

Properties

dev: T
ino: T
mode: T
nlink: T
uid: T
gid: T
rdev: T
size: T
blksize: T
blocks: T
atimeMs: T
mtimeMs: T
ctimeMs: T
birthtimeMs: T
atime: Date
mtime: Date
ctime: Date
birthtime: Date

Methods

isFile(): boolean
isDirectory(): boolean
isBlockDevice(): boolean
isCharacterDevice(): boolean
isSymbolicLink(): boolean
isFIFO(): boolean
isSocket(): boolean

class StatsFs

Usage in Deno

import { StatsFs } from "node:fs";

Provides information about a mounted file system.

Objects returned from statfs and its synchronous counterpart are of this type. If bigint in the options passed to those methods is true, the numeric values will be bigint instead of number.

StatFs {
  type: 1397114950,
  bsize: 4096,
  blocks: 121938943,
  bfree: 61058895,
  bavail: 61058895,
  files: 999,
  ffree: 1000000
}

bigint version:

StatFs {
  type: 1397114950n,
  bsize: 4096n,
  blocks: 121938943n,
  bfree: 61058895n,
  bavail: 61058895n,
  files: 999n,
  ffree: 1000000n
}

interface StatsFs

extends StatsFsBase<number>

interface StatsFsBase

Usage in Deno

import { type StatsFsBase } from "node:fs";

Type Parameters

T

Properties

type: T

Type of file system.

bsize: T

Optimal transfer block size.

blocks: T

Total data blocks in file system.

bfree: T

Free blocks in file system.

bavail: T

Available blocks for unprivileged users

files: T

Total file nodes in file system.

ffree: T

Free file nodes in file system.


interface StatSyncFn

extends Function

Usage in Deno

import { type StatSyncFn } from "node:fs";

Call Signatures

(
path: PathLike,
options?: undefined,
): Stats
(
path: PathLike,
options?: StatSyncOptions & { bigint?: false | undefined; throwIfNoEntry: false; },
): Stats | undefined
(
path: PathLike,
options: StatSyncOptions & { bigint: true; throwIfNoEntry: false; },
): BigIntStats | undefined
(
path: PathLike,
options?: StatSyncOptions & { bigint?: false | undefined; },
): Stats
(
path: PathLike,
options: StatSyncOptions & { bigint: true; },
): BigIntStats
(
path: PathLike,
options: StatSyncOptions & { bigint: boolean; throwIfNoEntry?: false | undefined; },
): Stats | BigIntStats
(
path: PathLike,
options?: StatSyncOptions,
):
Stats
| BigIntStats
| undefined

interface StatSyncOptions

extends StatOptions

Usage in Deno

import { type StatSyncOptions } from "node:fs";

Properties

throwIfNoEntry: boolean | undefined
optional

interface StatWatcher

extends EventEmitter

Usage in Deno

import { type StatWatcher } from "node:fs";

Class: fs.StatWatcher

Methods

ref(): this

When called, requests that the Node.js event loop not exit so long as the fs.StatWatcher is active. Calling watcher.ref() multiple times will have no effect.

By default, all fs.StatWatcher objects are "ref'ed", making it normally unnecessary to call watcher.ref() unless watcher.unref() had been called previously.

unref(): this

When called, the active fs.StatWatcher object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the fs.StatWatcher object's callback is invoked. Calling watcher.unref() multiple times will have no effect.


interface StreamOptions

Usage in Deno

import { type StreamOptions } from "node:fs";

Properties

flags: string | undefined
optional
encoding: BufferEncoding | undefined
optional
fd:
number
| promises.FileHandle
| undefined
optional
mode: number | undefined
optional
autoClose: boolean | undefined
optional
emitClose: boolean | undefined
optional
start: number | undefined
optional
signal:
AbortSignal
| null
| undefined
optional
highWaterMark: number | undefined
optional

interface WatchFileOptions

Usage in Deno

import { type WatchFileOptions } from "node:fs";

Watch for changes on filename. The callback listener will be called each time the file is accessed.

The options argument may be omitted. If provided, it should be an object. The options object may contain a boolean named persistent that indicates whether the process should continue to run as long as files are being watched. The options object may specify an interval property indicating how often the target should be polled in milliseconds.

The listener gets two arguments the current stat object and the previous stat object:

import { watchFile } from 'node:fs';

watchFile('message.text', (curr, prev) => {
  console.log(`the current mtime is: ${curr.mtime}`);
  console.log(`the previous mtime was: ${prev.mtime}`);
});

These stat objects are instances of fs.Stat. If the bigint option is true, the numeric values in these objects are specified as BigInts.

To be notified when the file was modified, not just accessed, it is necessary to compare curr.mtimeMs and prev.mtimeMs.

When an fs.watchFile operation results in an ENOENT error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.

Using watch is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.

When a file being watched by fs.watchFile() disappears and reappears, then the contents of previous in the second callback event (the file's reappearance) will be the same as the contents of previous in the first callback event (its disappearance).

This happens when:

  • the file is deleted, followed by a restore
  • the file is renamed and then renamed a second time back to its original name

Properties

bigint: boolean | undefined
optional
persistent: boolean | undefined
optional
interval: number | undefined
optional

interface WatchOptions

extends Abortable

Usage in Deno

import { type WatchOptions } from "node:fs";

Properties

encoding:
BufferEncoding
| "buffer"
| undefined
optional
persistent: boolean | undefined
optional
recursive: boolean | undefined
optional

interface WriteStreamOptions

extends StreamOptions

Usage in Deno

import { type WriteStreamOptions } from "node:fs";

Properties

fs:
CreateWriteStreamFSImplementation
| null
| undefined
optional
flush: boolean | undefined
optional

interface WriteVResult

Usage in Deno

import { type WriteVResult } from "node:fs";

Properties

bytesWritten: number
buffers: ArrayBufferView[]

namespace constants

Usage in Deno

import { constants } from "node:fs";

Variables

constants.COPYFILE_EXCL

Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists.

constants.COPYFILE_FICLONE

Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used.

constants.COPYFILE_FICLONE_FORCE

Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then the operation will fail with an error.

constants.F_OK

Constant for fs.access(). File is visible to the calling process.

constants.O_APPEND

Constant for fs.open(). Flag indicating that data will be appended to the end of the file.

constants.O_CREAT

Constant for fs.open(). Flag indicating to create the file if it does not already exist.

constants.O_DIRECT

Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O.

constants.O_DIRECTORY

Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory.

constants.O_DSYNC

Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity.

constants.O_EXCL

Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists.

constants.O_NOATIME

constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only.

constants.O_NOCTTY

Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one).

constants.O_NOFOLLOW

Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link.

constants.O_NONBLOCK

Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible.

constants.O_RDONLY

Constant for fs.open(). Flag indicating to open a file for read-only access.

constants.O_RDWR

Constant for fs.open(). Flag indicating to open a file for read-write access.

constants.O_SYMLINK

Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to.

constants.O_SYNC

Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O.

constants.O_TRUNC

Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero.

constants.O_WRONLY

Constant for fs.open(). Flag indicating to open a file for write-only access.

constants.R_OK

Constant for fs.access(). File can be read by the calling process.

constants.S_IFBLK

Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file.

constants.S_IFCHR

Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file.

constants.S_IFDIR

Constant for fs.Stats mode property for determining a file's type. File type constant for a directory.

constants.S_IFIFO

Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe.

constants.S_IFLNK

Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link.

constants.S_IFMT

Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code.

constants.S_IFREG

Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file.

constants.S_IFSOCK

Constant for fs.Stats mode property for determining a file's type. File type constant for a socket.

constants.S_IRGRP

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group.

constants.S_IROTH

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others.

constants.S_IRUSR

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner.

constants.S_IRWXG

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group.

constants.S_IRWXO

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others.

constants.S_IRWXU

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner.

constants.S_IWGRP

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group.

constants.S_IWOTH

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others.

constants.S_IWUSR

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner.

constants.S_IXGRP

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group.

constants.S_IXOTH

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others.

constants.S_IXUSR

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner.

constants.UV_FS_O_FILEMAP

When set, a memory file mapping is used to access the file. This flag is available on Windows operating systems only. On other operating systems, this flag is ignored.

constants.W_OK

Constant for fs.access(). File can be written by the calling process.

constants.X_OK

Constant for fs.access(). File can be executed by the calling process.


namespace promises

Usage in Deno

import { promises } from "node:fs";

The fs/promises API provides asynchronous file system methods that return promises.

The promise APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur.

Functions

promises.access

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_OK or 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.

promises.appendFile

Asynchronously append data to a file, creating the file if it does not yet exist. data can be a string or a Buffer.

promises.chmod

Changes the permissions of a file.

promises.chown

Changes the ownership of a file.

promises.copyFile

Asynchronously copies src to dest. By default, dest is overwritten if it already exists.

promises.cp

Asynchronously copies the entire directory structure from src to dest, including subdirectories and files.

promises.glob

Retrieves the files matching the specified pattern.

promises.lchown

Changes the ownership on a symbolic link.

promises.link

Creates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail.

promises.lstat

Equivalent to fsPromises.stat() unless path refers to a symbolic link, in which case the link itself is stat-ed, not the file that it refers to. Refer to the POSIX lstat(2) document for more detail.

promises.lutimes

Changes the access and modification times of a file in the same way as fsPromises.utimes(), with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed.

promises.mkdir

Asynchronously creates a directory.

promises.mkdtemp

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.

promises.open

Opens a FileHandle.

promises.opendir

Asynchronously open a directory for iterative scanning. See the POSIX opendir(3) documentation for more detail.

promises.readdir

Reads the contents of a directory.

promises.readFile

Asynchronously reads the entire contents of a file.

promises.readlink

Reads the contents of the symbolic link referred to by path. See the POSIX readlink(2) documentation for more detail. The promise is fulfilled with thelinkString upon success.

promises.realpath

Determines the actual location of path using the same semantics as the fs.realpath.native() function.

promises.rename

Renames oldPath to newPath.

promises.rm

Removes files and directories (modeled on the standard POSIX rm utility).

promises.rmdir

Removes the directory identified by path.

promises.stat
No documentation available
promises.statfs
No documentation available
promises.symlink

Creates a symbolic link.

promises.truncate

Truncates (shortens or extends the length) of the content at path to len bytes.

promises.unlink

If path refers to a symbolic link, then the link is removed without affecting the file or directory to which that link refers. If the path refers to a file path that is not a symbolic link, the file is deleted. See the POSIX unlink(2) documentation for more detail.

promises.utimes

Change the file system timestamps of the object referenced by path.

promises.watch

Returns an async iterator that watches for changes on filename, where filenameis either a file or a directory.

promises.writeFile

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.

promises.lchmod
No documentation available

Interfaces

promises.CreateReadStreamOptions
No documentation available
  • autoClose
  • emitClose
  • encoding
  • end
  • highWaterMark
  • start
promises.CreateWriteStreamOptions
No documentation available
  • autoClose
  • emitClose
  • encoding
  • flush
  • highWaterMark
  • start
promises.FileChangeInfo
No documentation available
  • eventType
  • filename
promises.FileHandle
No documentation available
  • appendFile
  • chmod
  • chown
  • close
  • createReadStream
  • createWriteStream
  • datasync
  • fd
  • read
  • readFile
  • readLines
  • readableWebStream
  • readv
  • stat
  • sync
  • truncate
  • utimes
  • write
  • writeFile
  • writev
promises.FileReadOptions
No documentation available
  • buffer
  • length
  • offset
  • position
promises.FileReadResult
No documentation available
  • buffer
  • bytesRead
promises.FlagAndOpenMode
No documentation available
  • flag
  • mode
promises.ReadableWebStreamOptions
No documentation available
  • type

Variables

promises.constants
No documentation available

type alias BigIntStatsListener

Usage in Deno

import { type BigIntStatsListener } from "node:fs";

Definition

(
curr: BigIntStats,
prev: BigIntStats,
) => void

type alias BufferEncodingOption

Usage in Deno

import { type BufferEncodingOption } from "node:fs";

Definition

"buffer" | { encoding: "buffer"; }

type alias CustomEvents

Usage in Deno

import { type CustomEvents } from "node:fs";

string & {} allows to allow any kind of strings for the event but still allows to have auto completion for the normal events.

Definition

[Key in string & { } | symbol]: (...args: any[]) => void

type alias EncodingOption

Usage in Deno

import { type EncodingOption } from "node:fs";

Definition

ObjectEncodingOptions
| BufferEncoding
| undefined
| null

type alias Mode

Usage in Deno

import { type Mode } from "node:fs";

Definition

number | string

type alias NoParamCallback

Usage in Deno

import { type NoParamCallback } from "node:fs";

Definition

(err: ErrnoException | null) => void

type alias OpenMode

Usage in Deno

import { type OpenMode } from "node:fs";

Definition

number | string

type alias PathLike

Usage in Deno

import { type PathLike } from "node:fs";

Valid types for path values in "fs".

Definition

string
| Buffer
| URL

type alias PathOrFileDescriptor

Usage in Deno

import { type PathOrFileDescriptor } from "node:fs";

Definition

PathLike | number

type alias ReadPosition

Usage in Deno

import { type ReadPosition } from "node:fs";

Definition

number | bigint

type alias ReadStreamEvents

Usage in Deno

import { type ReadStreamEvents } from "node:fs";

The Keys are events of the ReadStream and the values are the functions that are called when the event is emitted.

Definition

{ close: () => void; data: (chunk: Buffer | string) => void; end: () => void; error: (err: Error) => void; open: (fd: number) => void; pause: () => void; readable: () => void; ready: () => void; resume: () => void; } & CustomEvents

type alias StatsListener

Usage in Deno

import { type StatsListener } from "node:fs";

Definition

(
curr: Stats,
prev: Stats,
) => void

type alias symlink.Type

Usage in Deno

import { symlink } from "node:fs";

Definition

"dir"
| "file"
| "junction"

type alias TimeLike

Usage in Deno

import { type TimeLike } from "node:fs";

Definition

string
| number
| Date

type alias WatchEventType

Usage in Deno

import { type WatchEventType } from "node:fs";

Definition

"rename" | "change"

type alias WatchListener

Usage in Deno

import { type WatchListener } from "node:fs";

Type Parameters

T

Definition

(
event: WatchEventType,
filename: T | null,
) => void

type alias WriteFileOptions

Usage in Deno

import { type WriteFileOptions } from "node:fs";

Definition

(
ObjectEncodingOptions
& Abortable
& { mode?: Mode | undefined; flag?: string | undefined; flush?: boolean | undefined; }
)

| BufferEncoding
| null

type alias WriteStreamEvents

Usage in Deno

import { type WriteStreamEvents } from "node:fs";

The Keys are events of the WriteStream and the values are the functions that are called when the event is emitted.

Definition

{ close: () => void; drain: () => void; error: (err: Error) => void; finish: () => void; open: (fd: number) => void; pipe: (src: stream.Readable) => void; ready: () => void; unpipe: (src: stream.Readable) => void; } & CustomEvents

variable constants.COPYFILE_EXCL

Usage in Deno

import { constants } from "node:fs";

Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists.

Type

number

variable constants.COPYFILE_FICLONE

Usage in Deno

import { constants } from "node:fs";

Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used.

Type

number

variable constants.COPYFILE_FICLONE_FORCE

Usage in Deno

import { constants } from "node:fs";

Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then the operation will fail with an error.

Type

number

variable constants.F_OK

Usage in Deno

import { constants } from "node:fs";

Constant for fs.access(). File is visible to the calling process.

Type

number

variable constants.O_APPEND

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating that data will be appended to the end of the file.

Type

number

variable constants.O_CREAT

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating to create the file if it does not already exist.

Type

number

variable constants.O_DIRECT

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O.

Type

number

variable constants.O_DIRECTORY

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory.

Type

number

variable constants.O_DSYNC

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity.

Type

number

variable constants.O_EXCL

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists.

Type

number

variable constants.O_NOATIME

Usage in Deno

import { constants } from "node:fs";

constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only.

Type

number

variable constants.O_NOCTTY

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one).

Type

number

variable constants.O_NOFOLLOW

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link.

Type

number

variable constants.O_NONBLOCK

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible.

Type

number

variable constants.O_RDONLY

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating to open a file for read-only access.

Type

number

variable constants.O_RDWR

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating to open a file for read-write access.

Type

number

variable constants.O_SYMLINK

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to.

Type

number

variable constants.O_SYNC

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O.

Type

number

variable constants.O_TRUNC

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero.

Type

number

variable constants.O_WRONLY

Usage in Deno

import { constants } from "node:fs";

Constant for fs.open(). Flag indicating to open a file for write-only access.

Type

number

variable constants.R_OK

Usage in Deno

import { constants } from "node:fs";

Constant for fs.access(). File can be read by the calling process.

Type

number

variable constants.S_IFBLK

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file.

Type

number

variable constants.S_IFCHR

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file.

Type

number

variable constants.S_IFDIR

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining a file's type. File type constant for a directory.

Type

number

variable constants.S_IFIFO

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe.

Type

number

variable constants.S_IFLNK

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link.

Type

number

variable constants.S_IFMT

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code.

Type

number

variable constants.S_IFREG

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file.

Type

number

variable constants.S_IFSOCK

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining a file's type. File type constant for a socket.

Type

number

variable constants.S_IRGRP

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group.

Type

number

variable constants.S_IROTH

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others.

Type

number

variable constants.S_IRUSR

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner.

Type

number

variable constants.S_IRWXG

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group.

Type

number

variable constants.S_IRWXO

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others.

Type

number

variable constants.S_IRWXU

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner.

Type

number

variable constants.S_IWGRP

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group.

Type

number

variable constants.S_IWOTH

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others.

Type

number

variable constants.S_IWUSR

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner.

Type

number

variable constants.S_IXGRP

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group.

Type

number

variable constants.S_IXOTH

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others.

Type

number

variable constants.S_IXUSR

Usage in Deno

import { constants } from "node:fs";

Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner.

Type

number

variable constants.UV_FS_O_FILEMAP

Usage in Deno

import { constants } from "node:fs";

When set, a memory file mapping is used to access the file. This flag is available on Windows operating systems only. On other operating systems, this flag is ignored.

Type

number

variable constants.W_OK

Usage in Deno

import { constants } from "node:fs";

Constant for fs.access(). File can be written by the calling process.

Type

number

variable constants.X_OK

Usage in Deno

import { constants } from "node:fs";

Constant for fs.access(). File can be executed by the calling process.

Type

number

variable lstatSync

Usage in Deno

import { lstatSync } from "node:fs";

Synchronous lstat(2) - Get file status. Does not dereference symbolic links.

Type

StatSyncFn

variable promises.constants

Usage in Deno

import { promises } from "node:fs";
const { constants } = promises;

Type

fsConstants

variable statSync

Usage in Deno

import { statSync } from "node:fs";

Synchronous stat(2) - Get file status.

Type

StatSyncFn

© 2018–2025 the Deno authors
Licensed under the MIT License.
https://docs.deno.com/api/node/fs

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API