Spec-Zone.ru › Deno 2

File System

File System APIs for working with files, directories, and file metadata. Includes functions for reading, writing, and manipulating file paths.

Eg Deno.readDir, Deno.readTextFile


class Deno.FsFile

implements Disposable

The Deno abstraction for reading and writing files.

This is the most straight forward way of handling files within Deno and is recommended over using the discrete functions within the Deno namespace.

using file = await Deno.open("/foo/bar.txt", { read: true });
const fileInfo = await file.stat();
if (fileInfo.isFile) {
  const buf = new Uint8Array(100);
  const numberOfBytesRead = await file.read(buf); // 11 bytes
  const text = new TextDecoder().decode(buf);  // "hello world"
}

Properties

readable: ReadableStream<Uint8Array<ArrayBuffer>>
readonly

A ReadableStream instance representing to the byte contents of the file. This makes it easy to interoperate with other web streams based APIs.

using file = await Deno.open("my_file.txt", { read: true });
const decoder = new TextDecoder();
for await (const chunk of file.readable) {
  console.log(decoder.decode(chunk));
}

Note that the readable stream takes ownership of the file: reading the stream to completion (or cancelling it) closes the file automatically, so you should not close the file yourself while the stream is still being consumed.

writable: WritableStream<Uint8Array<ArrayBufferLike>>
readonly

A WritableStream instance to write the contents of the file. This makes it easy to interoperate with other web streams based APIs.

const items = ["hello", "world"];
using file = await Deno.open("my_file.txt", { write: true });
const encoder = new TextEncoder();
const writer = file.writable.getWriter();
for (const item of items) {
  await writer.write(encoder.encode(item));
}

Note that the writable stream takes ownership of the file: closing or aborting the stream closes the file automatically, so you should not close the file yourself while the stream is still in use.

Methods

[Symbol.dispose](): void
close(): void

Close the file. Closing a file when you are finished with it is important to avoid leaking resources.

using file = await Deno.open("my_file.txt");
// do work with "file" object
isTerminal(): boolean

Checks if the file resource is a TTY (terminal).

// This example is system and context specific
using file = await Deno.open("/dev/tty6");
file.isTerminal(); // true
lock(exclusive?: boolean): Promise<void>

Acquire an advisory file-system lock for the file.

lockSync(exclusive?: boolean): void

Synchronously acquire an advisory file-system lock synchronously for the file.

read(p: Uint8Array): Promise<number | null>

Read the file into an array buffer (p).

Resolves to either the number of bytes read during the operation or EOF (null) if there was nothing more to read.

It is possible for a read to successfully return with 0 bytes. This does not indicate EOF.

It is not guaranteed that the full buffer will be read in a single call.

// if "/foo/bar.txt" contains the text "hello world":
using file = await Deno.open("/foo/bar.txt");
const buf = new Uint8Array(100);
const numberOfBytesRead = await file.read(buf); // 11 bytes
const text = new TextDecoder().decode(buf);  // "hello world"
readSync(p: Uint8Array): number | null

Synchronously read from the file into an array buffer (p).

Returns either the number of bytes read during the operation or EOF (null) if there was nothing more to read.

It is possible for a read to successfully return with 0 bytes. This does not indicate EOF.

It is not guaranteed that the full buffer will be read in a single call.

// if "/foo/bar.txt" contains the text "hello world":
using file = Deno.openSync("/foo/bar.txt");
const buf = new Uint8Array(100);
const numberOfBytesRead = file.readSync(buf); // 11 bytes
const text = new TextDecoder().decode(buf);  // "hello world"
seek(
offset: number | bigint,
whence: SeekMode,
): Promise<number>

Seek to the given offset under mode given by whence. The call resolves to the new position within the resource (bytes from the start).

// Given the file contains "Hello world" text, which is 11 bytes long:
using file = await Deno.open(
  "hello.txt",
  { read: true, write: true, truncate: true, create: true },
);
await file.write(new TextEncoder().encode("Hello world"));

// advance cursor 6 bytes
const cursorPosition = await file.seek(6, Deno.SeekMode.Start);
console.log(cursorPosition);  // 6
const buf = new Uint8Array(100);
await file.read(buf);
console.log(new TextDecoder().decode(buf)); // "world"

The seek modes work as follows:

// Given the file contains "Hello world" text, which is 11 bytes long:
const file = await Deno.open(
  "hello.txt",
  { read: true, write: true, truncate: true, create: true },
);
await file.write(new TextEncoder().encode("Hello world"));

// Seek 6 bytes from the start of the file
console.log(await file.seek(6, Deno.SeekMode.Start)); // "6"
// Seek 2 more bytes from the current position
console.log(await file.seek(2, Deno.SeekMode.Current)); // "8"
// Seek backwards 2 bytes from the end of the file
console.log(await file.seek(-2, Deno.SeekMode.End)); // "9" (i.e. 11-2)
seekSync(
offset: number | bigint,
whence: SeekMode,
): number

Synchronously seek to the given offset under mode given by whence. The new position within the resource (bytes from the start) is returned.

using file = Deno.openSync(
  "hello.txt",
  { read: true, write: true, truncate: true, create: true },
);
file.writeSync(new TextEncoder().encode("Hello world"));

// advance cursor 6 bytes
const cursorPosition = file.seekSync(6, Deno.SeekMode.Start);
console.log(cursorPosition);  // 6
const buf = new Uint8Array(100);
file.readSync(buf);
console.log(new TextDecoder().decode(buf)); // "world"

The seek modes work as follows:

// Given the file contains "Hello world" text, which is 11 bytes long:
using file = Deno.openSync(
  "hello.txt",
  { read: true, write: true, truncate: true, create: true },
);
file.writeSync(new TextEncoder().encode("Hello world"));

// Seek 6 bytes from the start of the file
console.log(file.seekSync(6, Deno.SeekMode.Start)); // "6"
// Seek 2 more bytes from the current position
console.log(file.seekSync(2, Deno.SeekMode.Current)); // "8"
// Seek backwards 2 bytes from the end of the file
console.log(file.seekSync(-2, Deno.SeekMode.End)); // "9" (i.e. 11-2)
setRaw(
mode: boolean,
options?: SetRawOptions,
): void

Set TTY to be under raw mode or not. In raw mode, characters are read and returned as is, without being processed. All special processing of characters by the terminal is disabled, including echoing input characters. Reading from a TTY device in raw mode is faster than reading from a TTY device in canonical mode.

using file = await Deno.open("/dev/tty6");
file.setRaw(true, { cbreak: true });
stat(): Promise<FileInfo>

Resolves to a Deno.FileInfo for the file.

import { assert } from "jsr:@std/assert";

using file = await Deno.open("hello.txt");
const fileInfo = await file.stat();
assert(fileInfo.isFile);
statSync(): FileInfo

Synchronously returns a Deno.FileInfo for the file.

import { assert } from "jsr:@std/assert";

using file = Deno.openSync("hello.txt")
const fileInfo = file.statSync();
assert(fileInfo.isFile);
sync(): Promise<void>

Flushes any pending data and metadata operations of the given file stream to disk.

const file = await Deno.open(
  "my_file.txt",
  { read: true, write: true, create: true },
);
await file.write(new TextEncoder().encode("Hello World"));
await file.truncate(1);
await file.sync();
console.log(await Deno.readTextFile("my_file.txt")); // H
syncData(): Promise<void>

Flushes any pending data operations of the given file stream to disk.

using file = await Deno.open(
 "my_file.txt",
 { read: true, write: true, create: true },
);
await file.write(new TextEncoder().encode("Hello World"));
await file.syncData();
console.log(await Deno.readTextFile("my_file.txt")); // Hello World
syncDataSync(): void

Synchronously flushes any pending data operations of the given file stream to disk.

using file = Deno.openSync(
 "my_file.txt",
 { read: true, write: true, create: true },
);
file.writeSync(new TextEncoder().encode("Hello World"));
file.syncDataSync();
console.log(Deno.readTextFileSync("my_file.txt")); // Hello World
syncSync(): void

Synchronously flushes any pending data and metadata operations of the given file stream to disk.

const file = Deno.openSync(
  "my_file.txt",
  { read: true, write: true, create: true },
);
file.writeSync(new TextEncoder().encode("Hello World"));
file.truncateSync(1);
file.syncSync();
console.log(Deno.readTextFileSync("my_file.txt")); // H
truncate(len?: number): Promise<void>

Truncates (or extends) the file to reach the specified len. If len is not specified, then the entire file contents are truncated.

Truncate the entire file

using file = await Deno.open("my_file.txt", { write: true });
await file.truncate();

Truncate part of the file

// if "my_file.txt" contains the text "hello world":
using file = await Deno.open("my_file.txt", { write: true });
await file.truncate(7);
const buf = new Uint8Array(100);
await file.read(buf);
const text = new TextDecoder().decode(buf); // "hello w"
truncateSync(len?: number): void

Synchronously truncates (or extends) the file to reach the specified len. If len is not specified, then the entire file contents are truncated.

Truncate the entire file

using file = Deno.openSync("my_file.txt", { write: true });
file.truncateSync();

Truncate part of the file

// if "my_file.txt" contains the text "hello world":
using file = Deno.openSync("my_file.txt", { write: true });
file.truncateSync(7);
const buf = new Uint8Array(100);
file.readSync(buf);
const text = new TextDecoder().decode(buf); // "hello w"
tryLock(exclusive?: boolean): Promise<boolean>

Try to acquire an advisory file-system lock for the file. Returns true if the lock was acquired, false if the file is already locked.

Unlike Deno.FsFile.lock, this method will not block if the lock cannot be acquired.

tryLockSync(exclusive?: boolean): boolean

Synchronously try to acquire an advisory file-system lock for the file. Returns true if the lock was acquired, false if the file is already locked.

Unlike Deno.FsFile.lockSync, this method will not block if the lock cannot be acquired.

unlock(): Promise<void>

Release an advisory file-system lock for the file.

unlockSync(): void

Synchronously release an advisory file-system lock for the file.

utime(
atime: number | Date,
mtime: number | Date,
): Promise<void>

Changes the access (atime) and modification (mtime) times of the file stream resource. Given times are either in seconds (UNIX epoch time) or as Date objects.

using file = await Deno.open("file.txt", { create: true, write: true });
await file.utime(1556495550, new Date());
utimeSync(
atime: number | Date,
mtime: number | Date,
): void

Synchronously changes the access (atime) and modification (mtime) times of the file stream resource. Given times are either in seconds (UNIX epoch time) or as Date objects.

using file = Deno.openSync("file.txt", { create: true, write: true });
file.utime(1556495550, new Date());
write(p: Uint8Array): Promise<number>

Write the contents of the array buffer (p) to the file.

Resolves to the number of bytes written.

It is not guaranteed that the full buffer will be written in a single call.

const encoder = new TextEncoder();
const data = encoder.encode("Hello world");
using file = await Deno.open("/foo/bar.txt", { write: true });
const bytesWritten = await file.write(data); // 11
writeSync(p: Uint8Array): number

Synchronously write the contents of the array buffer (p) to the file.

Returns the number of bytes written.

It is not guaranteed that the full buffer will be written in a single call.

const encoder = new TextEncoder();
const data = encoder.encode("Hello world");
using file = Deno.openSync("/foo/bar.txt", { write: true });
const bytesWritten = file.writeSync(data); // 11

function Deno.chmod

allow-write
chmod(
path: string | URL,
mode: number,
): Promise<void>

Changes the permission of a specific file/directory of specified path. Ignores the process's umask.

await Deno.chmod("/path/to/file", 0o666);

The mode is a sequence of 3 octal numbers. The first/left-most number specifies the permissions for the owner. The second number specifies the permissions for the group. The last/right-most number specifies the permissions for others. For example, with a mode of 0o764, the owner (7) can read/write/execute, the group (6) can read/write and everyone else (4) can read only.

Number Description
7 read, write, and execute
6 read and write
5 read and execute
4 read only
3 write and execute
2 write only
1 execute only
0 no permission

Note: On Windows, only the read and write permissions can be modified. Distinctions between owner, group, and others are not supported.

Requires allow-write permission.

Parameters

path: string | URL
mode: number

Return Type

Promise<void>

function Deno.chmodSync

allow-write
chmodSync(
path: string | URL,
mode: number,
): void

Synchronously changes the permission of a specific file/directory of specified path. Ignores the process's umask.

Deno.chmodSync("/path/to/file", 0o666);

For a full description, see Deno.chmod.

Requires allow-write permission.

Parameters

path: string | URL
mode: number

Return Type

void

function Deno.chown

allow-write
chown(
path: string | URL,
uid: number | null,
gid: number | null,
): Promise<void>

Change owner of a regular file or directory.

This functionality is not available on Windows.

await Deno.chown("myFile.txt", 1000, 1002);

Requires allow-write permission.

Throws Error (not implemented) if executed on Windows.

Parameters

path: string | URL

path to the file

uid: number | null

user id (UID) of the new owner, or null for no change

gid: number | null

group id (GID) of the new owner, or null for no change

Return Type

Promise<void>

function Deno.chownSync

allow-write
chownSync(
path: string | URL,
uid: number | null,
gid: number | null,
): void

Synchronously change owner of a regular file or directory.

This functionality is not available on Windows.

Deno.chownSync("myFile.txt", 1000, 1002);

Requires allow-write permission.

Throws Error (not implemented) if executed on Windows.

Parameters

path: string | URL

path to the file

uid: number | null

user id (UID) of the new owner, or null for no change

gid: number | null

group id (GID) of the new owner, or null for no change

Return Type

void

function Deno.copyFile

allow-read allow-write
copyFile(
fromPath: string | URL,
toPath: string | URL,
): Promise<void>

Copies the contents and permissions of one file to another specified path, by default creating a new file if needed, else overwriting. Fails if target path is a directory or is unwritable.

await Deno.copyFile("from.txt", "to.txt");

Requires allow-read permission on fromPath.

Requires allow-write permission on toPath.

Parameters

fromPath: string | URL
toPath: string | URL

Return Type

Promise<void>

function Deno.copyFileSync

allow-read allow-write
copyFileSync(
fromPath: string | URL,
toPath: string | URL,
): void

Synchronously copies the contents and permissions of one file to another specified path, by default creating a new file if needed, else overwriting. Fails if target path is a directory or is unwritable.

Deno.copyFileSync("from.txt", "to.txt");

Requires allow-read permission on fromPath.

Requires allow-write permission on toPath.

Parameters

fromPath: string | URL
toPath: string | URL

Return Type

void

function Deno.create

allow-read allow-write
create(path: string | URL): Promise<FsFile>

Creates a file if none exists or truncates an existing file and resolves to an instance of Deno.FsFile.

const file = await Deno.create("/foo/bar.txt");

Requires allow-read and allow-write permissions.

Parameters

path: string | URL

Return Type

Promise<FsFile>

function Deno.createSync

allow-read allow-write
createSync(path: string | URL): FsFile

Creates a file if none exists or truncates an existing file and returns an instance of Deno.FsFile.

const file = Deno.createSync("/foo/bar.txt");

Requires allow-read and allow-write permissions.

Parameters

path: string | URL

Return Type

FsFile

function Deno.link

allow-read allow-write
link(
oldpath: string,
newpath: string,
): Promise<void>

Creates newpath as a hard link to oldpath.

await Deno.link("old/name", "new/name");

Requires allow-read and allow-write permissions.

Parameters

oldpath: string
newpath: string

Return Type

Promise<void>

function Deno.linkSync

allow-read allow-write
linkSync(
oldpath: string,
newpath: string,
): void

Synchronously creates newpath as a hard link to oldpath.

Deno.linkSync("old/name", "new/name");

Requires allow-read and allow-write permissions.

Parameters

oldpath: string
newpath: string

Return Type

void

function Deno.lstat

allow-read
lstat(path: string | URL): Promise<FileInfo>

Resolves to a Deno.FileInfo for the specified path. If path is a symlink, information for the symlink will be returned instead of what it points to.

import { assert } from "jsr:@std/assert";
const fileInfo = await Deno.lstat("hello.txt");
assert(fileInfo.isFile);

Requires allow-read permission.

Parameters

path: string | URL

Return Type

Promise<FileInfo>

function Deno.lstatSync

allow-read
lstatSync(path: string | URL): FileInfo

Synchronously returns a Deno.FileInfo for the specified path. If path is a symlink, information for the symlink will be returned instead of what it points to.

import { assert } from "jsr:@std/assert";
const fileInfo = Deno.lstatSync("hello.txt");
assert(fileInfo.isFile);

Requires allow-read permission.

Parameters

path: string | URL

Return Type

FileInfo

function Deno.makeTempDir

allow-write
makeTempDir(options?: MakeTempOptions): Promise<string>

Creates a new temporary directory in the default directory for temporary files, unless dir is specified. Other optional options include prefixing and suffixing the directory name with prefix and suffix respectively.

This call resolves to the full path to the newly created directory.

Multiple programs calling this function simultaneously will create different directories. It is the caller's responsibility to remove the directory when no longer needed.

const tempDirName0 = await Deno.makeTempDir();  // e.g. /tmp/2894ea76
const tempDirName1 = await Deno.makeTempDir({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d

Requires allow-write permission.

Parameters

options: MakeTempOptions
optional

Return Type

Promise<string>

function Deno.makeTempDirSync

allow-write
makeTempDirSync(options?: MakeTempOptions): string

Synchronously creates a new temporary directory in the default directory for temporary files, unless dir is specified. Other optional options include prefixing and suffixing the directory name with prefix and suffix respectively.

The full path to the newly created directory is returned.

Multiple programs calling this function simultaneously will create different directories. It is the caller's responsibility to remove the directory when no longer needed.

const tempDirName0 = Deno.makeTempDirSync();  // e.g. /tmp/2894ea76
const tempDirName1 = Deno.makeTempDirSync({ prefix: 'my_temp' });  // e.g. /tmp/my_temp339c944d

Requires allow-write permission.

Parameters

options: MakeTempOptions
optional

Return Type

string

function Deno.makeTempFile

allow-write
makeTempFile(options?: MakeTempOptions): Promise<string>

Creates a new temporary file in the default directory for temporary files, unless dir is specified.

Other options include prefixing and suffixing the directory name with prefix and suffix respectively.

This call resolves to the full path to the newly created file.

Multiple programs calling this function simultaneously will create different files. It is the caller's responsibility to remove the file when no longer needed.

const tmpFileName0 = await Deno.makeTempFile();  // e.g. /tmp/419e0bf2
const tmpFileName1 = await Deno.makeTempFile({ prefix: 'my_temp' });  // e.g. /tmp/my_temp754d3098

Requires allow-write permission.

Parameters

options: MakeTempOptions
optional

Return Type

Promise<string>

function Deno.makeTempFileSync

allow-write
makeTempFileSync(options?: MakeTempOptions): string

Synchronously creates a new temporary file in the default directory for temporary files, unless dir is specified.

Other options include prefixing and suffixing the directory name with prefix and suffix respectively.

The full path to the newly created file is returned.

Multiple programs calling this function simultaneously will create different files. It is the caller's responsibility to remove the file when no longer needed.

const tempFileName0 = Deno.makeTempFileSync(); // e.g. /tmp/419e0bf2
const tempFileName1 = Deno.makeTempFileSync({ prefix: 'my_temp' });  // e.g. /tmp/my_temp754d3098

Requires allow-write permission.

Parameters

options: MakeTempOptions
optional

Return Type

string

function Deno.mkdir

allow-write
mkdir(
path: string | URL,
options?: MkdirOptions,
): Promise<void>

Creates a new directory with the specified path.

await Deno.mkdir("new_dir");
await Deno.mkdir("nested/directories", { recursive: true });
await Deno.mkdir("restricted_access_dir", { mode: 0o700 });

Throws if the directory already exists, unless recursive is set to true.

Requires allow-write permission.

Parameters

path: string | URL
options: MkdirOptions
optional

Return Type

Promise<void>

function Deno.mkdirSync

allow-write
mkdirSync(
path: string | URL,
options?: MkdirOptions,
): void

Synchronously creates a new directory with the specified path.

Deno.mkdirSync("new_dir");
Deno.mkdirSync("nested/directories", { recursive: true });
Deno.mkdirSync("restricted_access_dir", { mode: 0o700 });

Throws if the directory already exists, unless recursive is set to true.

Requires allow-write permission.

Parameters

path: string | URL
options: MkdirOptions
optional

Return Type

void

function Deno.open

allow-read allow-write
open(
path: string | URL,
options?: OpenOptions,
): Promise<FsFile>

Open a file and resolve to an instance of Deno.FsFile. The file does not need to previously exist if using the create or createNew open options. The caller may have the resulting file automatically closed by the runtime once it's out of scope by declaring the file variable with the using keyword.

using file = await Deno.open("/foo/bar.txt", { read: true, write: true });
// Do work with file

Alternatively, the caller may manually close the resource when finished with it.

const file = await Deno.open("/foo/bar.txt", { read: true, write: true });
// Do work with file
file.close();

Requires allow-read and/or allow-write permissions depending on options.

Parameters

path: string | URL
options: OpenOptions
optional

Return Type

Promise<FsFile>

function Deno.openSync

allow-read allow-write
openSync(
path: string | URL,
options?: OpenOptions,
): FsFile

Synchronously open a file and return an instance of Deno.FsFile. The file does not need to previously exist if using the create or createNew open options. The caller may have the resulting file automatically closed by the runtime once it's out of scope by declaring the file variable with the using keyword.

using file = Deno.openSync("/foo/bar.txt", { read: true, write: true });
// Do work with file

Alternatively, the caller may manually close the resource when finished with it.

const file = Deno.openSync("/foo/bar.txt", { read: true, write: true });
// Do work with file
file.close();

Requires allow-read and/or allow-write permissions depending on options.

Parameters

path: string | URL
options: OpenOptions
optional

Return Type

FsFile

function Deno.readDir

allow-read
readDir(path: string | URL): AsyncIterable<DirEntry>

Reads the directory given by path and returns an async iterable of Deno.DirEntry. The order of entries is not guaranteed.

for await (const dirEntry of Deno.readDir("/")) {
  console.log(dirEntry.name);
}

Throws error if path is not a directory.

Requires allow-read permission.

Parameters

path: string | URL

Return Type

AsyncIterable<DirEntry>

function Deno.readDirSync

allow-read
readDirSync(path: string | URL): IteratorObject<DirEntry>

Synchronously reads the directory given by path and returns an iterable of Deno.DirEntry. The order of entries is not guaranteed.

for (const dirEntry of Deno.readDirSync("/")) {
  console.log(dirEntry.name);
}

Throws error if path is not a directory.

Requires allow-read permission.

Parameters

path: string | URL

Return Type

IteratorObject<DirEntry>

function Deno.readFile

allow-read
readFile(
path: string | URL,
options?: ReadFileOptions,
): Promise<Uint8Array<ArrayBuffer>>

Reads and resolves to the entire contents of a file as an array of bytes. TextDecoder can be used to transform the bytes to string if required. Rejects with an error when reading a directory.

const decoder = new TextDecoder("utf-8");
const data = await Deno.readFile("hello.txt");
console.log(decoder.decode(data));

Requires allow-read permission.

Parameters

path: string | URL
options: ReadFileOptions
optional

Return Type

Promise<Uint8Array<ArrayBuffer>>

function Deno.readFileSync

allow-read
readFileSync(path: string | URL): Uint8Array<ArrayBuffer>

Synchronously reads and returns the entire contents of a file as an array of bytes. TextDecoder can be used to transform the bytes to string if required. Throws an error when reading a directory.

const decoder = new TextDecoder("utf-8");
const data = Deno.readFileSync("hello.txt");
console.log(decoder.decode(data));

Requires allow-read permission.

Parameters

path: string | URL

Return Type

Uint8Array<ArrayBuffer>

function Deno.readLink

allow-read
readLink(path: string | URL): Promise<string>

Resolves to the full path destination of the named symbolic link.

await Deno.symlink("./test.txt", "./test_link.txt");
const target = await Deno.readLink("./test_link.txt"); // full path of ./test.txt

Throws TypeError if called with a hard link.

Requires allow-read permission.

Parameters

path: string | URL

Return Type

Promise<string>

function Deno.readLinkSync

allow-read
readLinkSync(path: string | URL): string

Synchronously returns the full path destination of the named symbolic link.

Deno.symlinkSync("./test.txt", "./test_link.txt");
const target = Deno.readLinkSync("./test_link.txt"); // full path of ./test.txt

Throws TypeError if called with a hard link.

Requires allow-read permission.

Parameters

path: string | URL

Return Type

string

function Deno.readTextFile

allow-read
readTextFile(
path: string | URL,
options?: ReadFileOptions,
): Promise<string>

Asynchronously reads and returns the entire contents of a file as an UTF-8 decoded string.

const data = await Deno.readTextFile("hello.txt");
console.log(data);

The returned promise rejects if the operation fails, for example with Deno.errors.NotFound if the file does not exist, Deno.errors.IsADirectory if path refers to a directory, or Deno.errors.PermissionDenied if the required permission has not been granted.

Requires allow-read permission.

Parameters

path: string | URL
options: ReadFileOptions
optional

Return Type

Promise<string>

function Deno.readTextFileSync

allow-read
readTextFileSync(path: string | URL): string

Synchronously reads and returns the entire contents of a file as an UTF-8 decoded string.

const data = Deno.readTextFileSync("hello.txt");
console.log(data);

Throws if the operation fails, for example with Deno.errors.NotFound if the file does not exist, Deno.errors.IsADirectory if path refers to a directory, or Deno.errors.PermissionDenied if the required permission has not been granted.

Requires allow-read permission.

Parameters

path: string | URL

Return Type

string

function Deno.realPath

allow-read
realPath(path: string | URL): Promise<string>

Resolves to the absolute normalized path, with symbolic links resolved.

// e.g. given /home/alice/file.txt and current directory /home/alice
await Deno.symlink("file.txt", "symlink_file.txt");
const realPath = await Deno.realPath("./file.txt");
const realSymLinkPath = await Deno.realPath("./symlink_file.txt");
console.log(realPath);  // outputs "/home/alice/file.txt"
console.log(realSymLinkPath);  // outputs "/home/alice/file.txt"

Requires allow-read permission for the target path.

Also requires allow-read permission for the CWD if the target path is relative.

Parameters

path: string | URL

Return Type

Promise<string>

function Deno.realPathSync

allow-read
realPathSync(path: string | URL): string

Synchronously returns absolute normalized path, with symbolic links resolved.

// e.g. given /home/alice/file.txt and current directory /home/alice
Deno.symlinkSync("file.txt", "symlink_file.txt");
const realPath = Deno.realPathSync("./file.txt");
const realSymLinkPath = Deno.realPathSync("./symlink_file.txt");
console.log(realPath);  // outputs "/home/alice/file.txt"
console.log(realSymLinkPath);  // outputs "/home/alice/file.txt"

Requires allow-read permission for the target path.

Also requires allow-read permission for the CWD if the target path is relative.

Parameters

path: string | URL

Return Type

string

function Deno.remove

allow-write
remove(
path: string | URL,
options?: RemoveOptions,
): Promise<void>

Removes the named file or directory.

await Deno.remove("/path/to/empty_dir/or/file");
await Deno.remove("/path/to/populated_dir/or/file", { recursive: true });

Throws error if permission denied, path not found, or path is a non-empty directory and the recursive option isn't set to true.

Requires allow-write permission.

Parameters

path: string | URL
options: RemoveOptions
optional

Return Type

Promise<void>

function Deno.removeSync

allow-write
removeSync(
path: string | URL,
options?: RemoveOptions,
): void

Synchronously removes the named file or directory.

Deno.removeSync("/path/to/empty_dir/or/file");
Deno.removeSync("/path/to/populated_dir/or/file", { recursive: true });

Throws error if permission denied, path not found, or path is a non-empty directory and the recursive option isn't set to true.

Requires allow-write permission.

Parameters

path: string | URL
options: RemoveOptions
optional

Return Type

void

function Deno.rename

allow-read allow-write
rename(
oldpath: string | URL,
newpath: string | URL,
): Promise<void>

Renames (moves) oldpath to newpath. Paths may be files or directories. If newpath already exists and is not a directory, rename() replaces it. OS-specific restrictions may apply when oldpath and newpath are in different directories.

await Deno.rename("old/path", "new/path");

On Unix-like OSes, this operation does not follow symlinks at either path.

It varies between platforms when the operation throws errors, and if so what they are. It's always an error to rename anything to a non-empty directory.

Requires allow-read and allow-write permissions.

Parameters

oldpath: string | URL
newpath: string | URL

Return Type

Promise<void>

function Deno.renameSync

allow-read allow-write
renameSync(
oldpath: string | URL,
newpath: string | URL,
): void

Synchronously renames (moves) oldpath to newpath. Paths may be files or directories. If newpath already exists and is not a directory, renameSync() replaces it. OS-specific restrictions may apply when oldpath and newpath are in different directories.

Deno.renameSync("old/path", "new/path");

On Unix-like OSes, this operation does not follow symlinks at either path.

It varies between platforms when the operation throws errors, and if so what they are. It's always an error to rename anything to a non-empty directory.

Requires allow-read and allow-write permissions.

Parameters

oldpath: string | URL
newpath: string | URL

Return Type

void

function Deno.stat

allow-read
stat(path: string | URL): Promise<FileInfo>

Resolves to a Deno.FileInfo for the specified path. Will always follow symlinks.

import { assert } from "jsr:@std/assert";
const fileInfo = await Deno.stat("hello.txt");
assert(fileInfo.isFile);

Requires allow-read permission.

Parameters

path: string | URL

Return Type

Promise<FileInfo>

function Deno.statSync

allow-read
statSync(path: string | URL): FileInfo

Synchronously returns a Deno.FileInfo for the specified path. Will always follow symlinks.

import { assert } from "jsr:@std/assert";
const fileInfo = Deno.statSync("hello.txt");
assert(fileInfo.isFile);

Requires allow-read permission.

Parameters

path: string | URL

Return Type

FileInfo

function Deno.symlink

allow-read allow-write
symlink(
oldpath: string | URL,
newpath: string | URL,
options?: SymlinkOptions,
): Promise<void>

Creates newpath as a symbolic link to oldpath.

The options.type parameter can be set to "file", "dir" or "junction". This argument is only available on Windows and ignored on other platforms.

await Deno.symlink("old/name", "new/name");

Requires allow-read and allow-write permissions granted without a path scope (i.e. --allow-read --allow-write, not --allow-read=./dir --allow-write=./dir). A symlink's target may be a relative, absolute, or not-yet-existing path that is only resolved when the link is later traversed, so it cannot be checked against a path-scoped allow-list at creation time. Path-scoped grants are therefore rejected.

Parameters

oldpath: string | URL
newpath: string | URL
options: SymlinkOptions
optional

Return Type

Promise<void>

function Deno.symlinkSync

allow-read allow-write
symlinkSync(
oldpath: string | URL,
newpath: string | URL,
options?: SymlinkOptions,
): void

Creates newpath as a symbolic link to oldpath.

The options.type parameter can be set to "file", "dir" or "junction". This argument is only available on Windows and ignored on other platforms.

Deno.symlinkSync("old/name", "new/name");

Requires allow-read and allow-write permissions granted without a path scope (i.e. --allow-read --allow-write, not --allow-read=./dir --allow-write=./dir). A symlink's target may be a relative, absolute, or not-yet-existing path that is only resolved when the link is later traversed, so it cannot be checked against a path-scoped allow-list at creation time. Path-scoped grants are therefore rejected.

Parameters

oldpath: string | URL
newpath: string | URL
options: SymlinkOptions
optional

Return Type

void

function Deno.truncate

allow-write
truncate(
name: string,
len?: number,
): Promise<void>

Truncates (or extends) the specified file, to reach the specified len. If len is not specified then the entire file contents are truncated.

Truncate the entire file

await Deno.truncate("my_file.txt");

Truncate part of the file

const file = await Deno.makeTempFile();
await Deno.writeTextFile(file, "Hello World");
await Deno.truncate(file, 7);
const data = await Deno.readFile(file);
console.log(new TextDecoder().decode(data));  // "Hello W"

Requires allow-write permission.

Parameters

name: string
len: number
optional

Return Type

Promise<void>

function Deno.truncateSync

allow-write
truncateSync(
name: string,
len?: number,
): void

Synchronously truncates (or extends) the specified file, to reach the specified len. If len is not specified then the entire file contents are truncated.

Truncate the entire file

Deno.truncateSync("my_file.txt");

Truncate part of the file

const file = Deno.makeTempFileSync();
Deno.writeFileSync(file, new TextEncoder().encode("Hello World"));
Deno.truncateSync(file, 7);
const data = Deno.readFileSync(file);
console.log(new TextDecoder().decode(data));

Requires allow-write permission.

Parameters

name: string
len: number
optional

Return Type

void

function Deno.umask

allow-sys
umask(mask?: number): number

Retrieve the process umask. If mask is provided, sets the process umask. This call always returns what the umask was before the call.

console.log(Deno.umask());  // e.g. 18 (0o022)
const prevUmaskValue = Deno.umask(0o077);  // e.g. 18 (0o022)
console.log(Deno.umask());  // e.g. 63 (0o077)

Requires allow-sys="umask" permission.

Note: This API is not implemented on Windows

Parameters

mask: number
optional

Return Type

number

function Deno.utime

allow-write
utime(
path: string | URL,
atime: number | Date,
mtime: number | Date,
): Promise<void>

Changes the access (atime) and modification (mtime) times of a file system object referenced by path. Given times are either in seconds (UNIX epoch time) or as Date objects.

await Deno.utime("myfile.txt", 1556495550, new Date());

Requires allow-write permission.

Parameters

path: string | URL
atime: number | Date
mtime: number | Date

Return Type

Promise<void>

function Deno.utimeSync

allow-write
utimeSync(
path: string | URL,
atime: number | Date,
mtime: number | Date,
): void

Synchronously changes the access (atime) and modification (mtime) times of a file system object referenced by path. Given times are either in seconds (UNIX epoch time) or as Date objects.

Deno.utimeSync("myfile.txt", 1556495550, new Date());

Requires allow-write permission.

Parameters

path: string | URL
atime: number | Date
mtime: number | Date

Return Type

void

function Deno.watchFs

allow-read
watchFs(
paths: string | string[],
options?: { recursive?: boolean; ignore?: string | string[]; },
): FsWatcher

Watch for file system events against one or more paths, which can be files or directories. These paths must exist already. One user action (e.g. touch test.file) can generate multiple file system events. Likewise, one user action can result in multiple file paths in one event (e.g. mv old_name.txt new_name.txt).

The recursive option is true by default and, for directories, will watch the specified directory and all sub directories.

Note that the exact ordering of the events can vary between operating systems.

const watcher = Deno.watchFs("/");
for await (const event of watcher) {
   console.log(">>>> event", event);
   // { kind: "create", paths: [ "/foo.txt" ] }
}

The ignore option can be used to filter out events for one or more paths. A path matches when it is, or is contained within, an ignored path, so ignoring a directory ignores everything beneath it. Relative paths are resolved against the current working directory. Ignored paths still require allow-read permission, the same as the watched paths.

// Watch the project but skip the `.git` directory and `build` output.
const watcher = Deno.watchFs(".", { ignore: [".git", "build"] });

Call watcher.close() to stop watching.

const watcher = Deno.watchFs("/");

setTimeout(() => {
  watcher.close();
}, 5000);

for await (const event of watcher) {
   console.log(">>>> event", event);
}

Requires allow-read permission.

Parameters

paths: string | string[]
options: { recursive?: boolean; ignore?: string | string[]; }
optional

Return Type

FsWatcher

function Deno.writeFile

allow-read allow-write
writeFile(
path: string | URL,
data: Uint8Array | ReadableStream<Uint8Array>,
options?: WriteFileOptions,
): Promise<void>

Write data to the given path, by default creating a new file if needed, else overwriting.

const encoder = new TextEncoder();
const data = encoder.encode("Hello world\n");
await Deno.writeFile("hello1.txt", data);  // overwrite "hello1.txt" or create it
await Deno.writeFile("hello2.txt", data, { create: false });  // only works if "hello2.txt" exists
await Deno.writeFile("hello3.txt", data, { mode: 0o777 });  // set permissions on new file
await Deno.writeFile("hello4.txt", data, { append: true });  // add data to the end of the file

Requires allow-write permission, and allow-read if options.create is false.

Parameters

path: string | URL
data: Uint8Array | ReadableStream<Uint8Array>
options: WriteFileOptions
optional

Return Type

Promise<void>

function Deno.writeFileSync

allow-read allow-write
writeFileSync(
path: string | URL,
data: Uint8Array,
options?: WriteFileOptions,
): void

Synchronously write data to the given path, by default creating a new file if needed, else overwriting.

const encoder = new TextEncoder();
const data = encoder.encode("Hello world\n");
Deno.writeFileSync("hello1.txt", data);  // overwrite "hello1.txt" or create it
Deno.writeFileSync("hello2.txt", data, { create: false });  // only works if "hello2.txt" exists
Deno.writeFileSync("hello3.txt", data, { mode: 0o777 });  // set permissions on new file
Deno.writeFileSync("hello4.txt", data, { append: true });  // add data to the end of the file

Requires allow-write permission, and allow-read if options.create is false.

Parameters

path: string | URL
data: Uint8Array
options: WriteFileOptions
optional

Return Type

void

function Deno.writeTextFile

allow-read allow-write
writeTextFile(
path: string | URL,
data: string | ReadableStream<string>,
options?: WriteFileOptions,
): Promise<void>

Write string data to the given path, by default creating a new file if needed, else overwriting.

await Deno.writeTextFile("hello1.txt", "Hello world\n");  // overwrite "hello1.txt" or create it

The data is written to the file and the file is closed, but this does not guarantee that the contents have been flushed from the operating system's buffers to the physical storage device. If you need such a durability guarantee (for example before signalling that a write has been committed), open the file with Deno.open and call Deno.FsFile.sync before closing it.

Requires allow-write permission, and allow-read if options.create is false.

Parameters

path: string | URL
data: string | ReadableStream<string>
options: WriteFileOptions
optional

Return Type

Promise<void>

function Deno.writeTextFileSync

allow-read allow-write
writeTextFileSync(
path: string | URL,
data: string,
options?: WriteFileOptions,
): void

Synchronously write string data to the given path, by default creating a new file if needed, else overwriting.

Deno.writeTextFileSync("hello1.txt", "Hello world\n");  // overwrite "hello1.txt" or create it

As with Deno.writeTextFile, the data is written and the file is closed, but this does not guarantee the contents have been flushed from the operating system's buffers to the physical storage device. If you need such a durability guarantee, open the file with Deno.openSync and call Deno.FsFile.syncSync before closing it.

Requires allow-write permission, and allow-read if options.create is false.

Parameters

path: string | URL
data: string
options: WriteFileOptions
optional

Return Type

void

interface Deno.DirEntry

Information about a directory entry returned from Deno.readDir and Deno.readDirSync.

Properties

name: string

The file name of the entry. It is just the entity name and does not include the full path.

isFile: boolean

True if this is info for a regular file. Mutually exclusive to DirEntry.isDirectory and DirEntry.isSymlink.

isDirectory: boolean

True if this is info for a regular directory. Mutually exclusive to DirEntry.isFile and DirEntry.isSymlink.

isSymlink: boolean

True if this is info for a symlink. Mutually exclusive to DirEntry.isFile and DirEntry.isDirectory.


interface Deno.FileInfo

Provides information about a file and is returned by Deno.stat, Deno.lstat, Deno.statSync, and Deno.lstatSync or from calling stat() and statSync() on an Deno.FsFile instance.

Properties

isFile: boolean

True if this is info for a regular file. Mutually exclusive to FileInfo.isDirectory and FileInfo.isSymlink.

isDirectory: boolean

True if this is info for a regular directory. Mutually exclusive to FileInfo.isFile and FileInfo.isSymlink.

isSymlink: boolean

True if this is info for a symlink. Mutually exclusive to FileInfo.isFile and FileInfo.isDirectory.

size: number

The size of the file, in bytes.

mtime: Date | null

The last modification time of the file. This corresponds to the mtime field from stat on Linux/Mac OS and ftLastWriteTime on Windows. This may not be available on all platforms.

atime: Date | null

The last access time of the file. This corresponds to the atime field from stat on Unix and ftLastAccessTime on Windows. This may not be available on all platforms.

birthtime: Date | null

The creation time of the file. This corresponds to the birthtime field from stat on Mac/BSD and ftCreationTime on Windows. This may not be available on all platforms.

ctime: Date | null

The last change time of the file. This corresponds to the ctime field from stat on Mac/BSD and ChangeTime on Windows. This may not be available on all platforms.

dev: number

ID of the device containing the file.

ino: number | null

Corresponds to the inode number on Unix systems. On Windows, this is the file index number that is unique within a volume. This may not be available on all platforms.

mode: number | null

The underlying raw st_mode bits that contain the standard Unix permissions for this file/directory.

nlink: number | null

Number of hard links pointing to this file.

uid: number | null

User ID of the owner of this file.

Linux/Mac OS only.

gid: number | null

Group ID of the owner of this file.

Linux/Mac OS only.

rdev: number | null

Device ID of this file.

Linux/Mac OS only.

blksize: number | null

Blocksize for filesystem I/O.

Linux/Mac OS only.

blocks: number | null

Number of blocks allocated to the file, in 512-byte units.

isBlockDevice: boolean | null

True if this is info for a block device.

Linux/Mac OS only.

isCharDevice: boolean | null

True if this is info for a char device.

Linux/Mac OS only.

isFifo: boolean | null

True if this is info for a fifo.

Linux/Mac OS only.

isSocket: boolean | null

True if this is info for a socket.

Linux/Mac OS only.


interface Deno.FsEvent

Represents a unique file system event yielded by a Deno.FsWatcher.

Properties

kind:
"any"
| "access"
| "create"
| "modify"
| "rename"
| "remove"
| "other"

The kind/type of the file system event.

paths: string[]

An array of paths that are associated with the file system event.

flag: FsEventFlag
optional

Any additional flags associated with the event.


interface Deno.FsWatcher

extends AsyncIterable<FsEvent>Disposable

Returned by Deno.watchFs. It is an async iterator yielding up system events. To stop watching the file system by calling .close() method.

Methods

close(): void

Stops watching the file system and closes the watcher resource.

return(value?: any): Promise<IteratorResult<FsEvent>>
optional

Stops watching the file system and closes the watcher resource.

[[Symbol.asyncIterator]](): AsyncIterableIterator<FsEvent>

interface Deno.MakeTempOptions

Options which can be set when using Deno.makeTempDir, Deno.makeTempDirSync, Deno.makeTempFile, and Deno.makeTempFileSync.

Properties

dir: string
optional

Directory where the temporary directory should be created (defaults to the env variable TMPDIR, or the system's default, usually /tmp).

Note that if the passed dir is relative, the path returned by makeTempFile() and makeTempDir() will also be relative. Be mindful of this when changing working directory.

prefix: string
optional

String that should precede the random portion of the temporary directory's name.

suffix: string
optional

String that should follow the random portion of the temporary directory's name.


interface Deno.MkdirOptions

Options which can be set when using Deno.mkdir and Deno.mkdirSync.

Properties

recursive: boolean = false
optional

If set to true, means that any intermediate directories will also be created (as with the shell command mkdir -p).

Intermediate directories are created with the same permissions.

When recursive is set to true, succeeds silently (without changing any permissions) if a directory already exists at the path, or if the path is a symlink to an existing directory.

mode: number
optional

Permissions to use when creating the directory (defaults to 0o777, before the process's umask).

Ignored on Windows.


interface Deno.OpenOptions

Options which can be set when doing Deno.open and Deno.openSync.

Properties

read: boolean = true
optional

Sets the option for read access. This option, when true, means that the file should be read-able if opened.

write: boolean = false
optional

Sets the option for write access. This option, when true, means that the file should be write-able if opened. If the file already exists, any write calls on it will overwrite its contents, by default without truncating it.

append: boolean = false
optional

Sets the option for the append mode. This option, when true, means that writes will append to a file instead of overwriting previous contents.

Note that setting { write: true, append: true } has the same effect as setting only { append: true }.

truncate: boolean = false
optional

Sets the option for truncating a previous file. If a file is successfully opened with this option set it will truncate the file to 0 size if it already exists. The file must be opened with write access for truncate to work.

create: boolean = false
optional

Sets the option to allow creating a new file, if one doesn't already exist at the specified path. Requires write or append access to be used.

createNew: boolean = false
optional

If set to true, no file, directory, or symlink is allowed to exist at the target location. Requires write or append access to be used. When createNew is set to true, create and truncate are ignored.

mode: number
optional

Permissions to use if creating the file (defaults to 0o666, before the process's umask).

Ignored on Windows.


interface Deno.ReadFileOptions

Options which can be set when using Deno.readFile or Deno.readFileSync.

Properties

signal: AbortSignal
optional

An abort signal to allow cancellation of the file read operation. If the signal becomes aborted the readFile operation will be stopped and the promise returned will be rejected with an AbortError.


interface Deno.RemoveOptions

Options which can be set when using Deno.remove and Deno.removeSync.

Properties

recursive: boolean = false
optional

If set to true, path will be removed even if it's a non-empty directory.


interface Deno.SymlinkOptions

Options that can be used with symlink and symlinkSync.

Properties

type:
"file"
| "dir"
| "junction"

Specify the symbolic link type as file, directory or NTFS junction. This option only applies to Windows and is ignored on other operating systems.


interface Deno.WriteFileOptions

Options for writing to a file.

Properties

append: boolean = false
optional

If set to true, will append to a file instead of overwriting previous contents.

create: boolean = true
optional

Sets the option to allow creating a new file, if one doesn't already exist at the specified path.

createNew: boolean = false
optional

If set to true, no file, directory, or symlink is allowed to exist at the target location. When createNew is set to true, create is ignored.

mode: number
optional

Permissions always applied to file.

signal: AbortSignal
optional

An abort signal to allow cancellation of the file write operation.

If the signal becomes aborted the write file operation will be stopped and the promise returned will be rejected with an AbortError.


type alias Deno.FsEventFlag

Additional information for FsEvent objects with the "other" kind.

  • "rescan": rescan notices indicate either a lapse in the events or a change in the filesystem such that events received so far can no longer be relied on to represent the state of the filesystem now. An application that simply reacts to file changes may not care about this. An application that keeps an in-memory representation of the filesystem will need to care, and will need to refresh that representation directly from the filesystem.

Definition

"rescan"

© 2018–2025 the Deno authors
Licensed under the MIT License.
https://docs.deno.com/api/deno/file-system

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API