选项
全部
  • Public
  • Public/Protected
  • 全部
菜单

索引

Enumerations

Classes

Interfaces

Type aliases

Variables

Functions

Type aliases

Addr

Arch

Arch: "x64" | "arm64"

DirKind

DirKind: "home" | "cache" | "config" | "executable" | "data" | "data_local" | "audio" | "desktop" | "document" | "download" | "font" | "picture" | "public" | "template" | "tmp" | "video"

UNSTABLE*

EOF

EOF: typeof EOF

OpenMode

OpenMode: "r" | "r+" | "w" | "w+" | "a" | "a+" | "x" | "x+"

一组字符串文本,用于指定如何打开文件。

A set of string literals which specify how to open a file.

描述
"r" 只读。默认值。从文件开头开始。
"r+" 可读写。从文件开头开始。
"w" 仅写入。打开并截取现有文件或者创建一个仅写入权限的新文件。
"w+" 可读写。打开并截取现有文件或者创建一个可读写权限的新文件。
"a" 仅写入。打开现有文件或者创建新文件。每次写入都会将内容追加到文件末尾。
"a+" 可读写。行为类似于 "a" 并且允许从文件中读取。
"x" 仅写入。专属创建 - 仅在文件不存在时创建新文件。
"x+" 可读写。行为类似于 "x" 并且允许从文件中读取。
Value Description
"r" Read-only. Default. Starts at beginning of file.
"r+" Read-write. Start at beginning of file.
"w" Write-only. Opens and truncates existing file or creates new one for writing only.
"w+" Read-write. Opens and truncates existing file or creates new one for writing and reading.
"a" Write-only. Opens existing file or creates new one. Each write appends content to the end of file.
"a+" Read-write. Behaves like "a" and allows to read from file.
"x" Write-only. Exclusive create - creates new file only if one doesn't exist already.
"x+" Read-write. Behaves like x and allows reading from file.

OperatingSystem

OperatingSystem: "mac" | "win" | "linux"

PermissionDescriptor

权限描述符,定义一个可以查询、请求或撤销的权限。

Permission descriptors which define a permission which can be queried, requested, or revoked.

PermissionName

PermissionName: "run" | "read" | "write" | "net" | "env" | "plugin" | "hrtime"

不稳定:希望与浏览器在名称上有更多的相同。

UNSTABLE*: potentially want names to overlap more with browser.

调用方授予的权限。

The permissions as granted by the caller.

PermissionState

PermissionState: "granted" | "denied" | "prompt"

权限的状态。

The current status of the permission.

ProcessStatus

ProcessStatus: { code: 0; signal?: undefined; success: true } | { code: number; signal?: number; success: false }

ProcessStdio

ProcessStdio: "inherit" | "piped" | "null"

如何处理子进程的 stdio。

How to handle subprocess stdio.

"inherit" 如果未指定,则为默认值。子进程继承父进程的 stdio。

"inherit" The default if unspecified. The child inherits from the corresponding parent descriptor.

"piped" 使用一个新管道来连接父子进程。

"piped" A new pipe should be arranged to connect the parent and child sub-processes.

"null" 输入输出流将被忽略。这相当于将流附加到了 /dev/null

"null" This stream will be ignored. This is the equivalent of attaching the stream to /dev/null.

Variables

Const EOF

EOF: keyof symbol

不稳定: 可能会移动到 Deno.symbols

UNSTABLE*: might move to Deno.symbols.

Const Signal

Signal: typeof MacOSSignal | typeof LinuxSignal

不稳定: make platform independent.

UNSTABLE*: make platform independent.

信号数字。此值是独立于平台的。

Signals numbers. This is platform dependent.

Const args

args: string[]

将脚本参数返回给程序。例如我们运行下方的程序

Returns the script arguments to the program. If for example we run a program:

 deno --allow-read https://deno.land/std/examples/cat.ts /etc/passwd

此时 Deno.args 将包含:

Then Deno.args will contain:

 [ "/etc/passwd" ]

Const build

build: BuildInfo

构建的相关信息。

Build related information.

Const errors

errors: { AddrInUse: ErrorConstructor; AddrNotAvailable: ErrorConstructor; AlreadyExists: ErrorConstructor; BadResource: ErrorConstructor; BrokenPipe: ErrorConstructor; Busy: ErrorConstructor; ConnectionAborted: ErrorConstructor; ConnectionRefused: ErrorConstructor; ConnectionReset: ErrorConstructor; Http: ErrorConstructor; Interrupted: ErrorConstructor; InvalidData: ErrorConstructor; NotConnected: ErrorConstructor; NotFound: ErrorConstructor; PermissionDenied: ErrorConstructor; TimedOut: ErrorConstructor; UnexpectedEof: ErrorConstructor; WriteZero: ErrorConstructor }

一些 Error 构造函数的集合,当 Deno API 抛出错误时会用到这些异常。

A set of error constructors that are raised by Deno APIs.

类型声明

  • AddrInUse: ErrorConstructor
  • AddrNotAvailable: ErrorConstructor
  • AlreadyExists: ErrorConstructor
  • BadResource: ErrorConstructor
  • BrokenPipe: ErrorConstructor
  • Busy: ErrorConstructor
  • ConnectionAborted: ErrorConstructor
  • ConnectionRefused: ErrorConstructor
  • ConnectionReset: ErrorConstructor
  • Http: ErrorConstructor
  • Interrupted: ErrorConstructor
  • InvalidData: ErrorConstructor
  • NotConnected: ErrorConstructor
  • NotFound: ErrorConstructor
  • PermissionDenied: ErrorConstructor
  • TimedOut: ErrorConstructor
  • UnexpectedEof: ErrorConstructor
  • WriteZero: ErrorConstructor

Let noColor

noColor: boolean

显示环境变量 NO_COLOR 的值。

Reflects the NO_COLOR environment variable.

Const permissions

permissions: Permissions

不稳定:可能移动到 navigator.permissions 以匹配 web API。

UNSTABLE*: maybe move to navigator.permissions to match web API.

Let pid

pid: number

当前正在运行的进程 ID。

The current process id of the runtime.

Const signals

signals: { alarm: () => SignalStream; child: () => SignalStream; hungup: () => SignalStream; interrupt: () => SignalStream; io: () => SignalStream; pipe: () => SignalStream; quit: () => SignalStream; terminate: () => SignalStream; userDefined1: () => SignalStream; userDefined2: () => SignalStream; windowChange: () => SignalStream }

不稳定: 新 API,没有经过审查。

UNSTABLE*: new API, yet to be vetted.

类型声明

  • alarm: () => SignalStream

    返回 SIGALRM 信号流。

    Returns the stream of SIGALRM signals.

    此方法是 Deno.signal(Deno.Signal.SIGALRM) 的简写形式。

    This method is the shorthand for Deno.signal(Deno.Signal.SIGALRM).

  • child: () => SignalStream

    返回 SIGCHLD 信号流。

    Returns the stream of SIGCHLD signals.

    此方法是 Deno.signal(Deno.Signal.SIGCHLD) 的简写形式。

    This method is the shorthand for Deno.signal(Deno.Signal.SIGCHLD).

  • hungup: () => SignalStream

    返回 SIGHUP 信号流。

    Returns the stream of SIGHUP signals.

    此方法是 Deno.signal(Deno.Signal.SIGHUP) 的简写形式。

    This method is the shorthand for Deno.signal(Deno.Signal.SIGHUP).

  • interrupt: () => SignalStream

    返回 SIGINT 信号流。

    Returns the stream of SIGINT signals.

    此方法是 Deno.signal(Deno.Signal.SIGINT) 的简写形式。

    This method is the shorthand for Deno.signal(Deno.Signal.SIGINT).

  • io: () => SignalStream

    返回 SIGIO 信号流。

    Returns the stream of SIGIO signals.

    此方法是 Deno.signal(Deno.Signal.SIGIO) 的简写形式。

    This method is the shorthand for Deno.signal(Deno.Signal.SIGIO).

  • pipe: () => SignalStream

    返回 SIGPIPE 信号流。

    Returns the stream of SIGPIPE signals.

    此方法是 Deno.signal(Deno.Signal.SIGPIPE) 的简写形式。

    This method is the shorthand for Deno.signal(Deno.Signal.SIGPIPE).

  • quit: () => SignalStream

    返回 SIGQUIT 信号流。

    Returns the stream of SIGQUIT signals.

    此方法是 Deno.signal(Deno.Signal.SIGQUIT) 的简写形式。

    This method is the shorthand for Deno.signal(Deno.Signal.SIGQUIT).

  • terminate: () => SignalStream

    返回 SIGTERM 信号流。

    Returns the stream of SIGTERM signals.

    此方法是 Deno.signal(Deno.Signal.SIGTERM) 的简写形式。

    This method is the shorthand for Deno.signal(Deno.Signal.SIGTERM).

  • userDefined1: () => SignalStream

    返回 SIGUSR1 信号流。

    Returns the stream of SIGUSR1 signals.

    此方法是 Deno.signal(Deno.Signal.SIGUSR1) 的简写形式。

    This method is the shorthand for Deno.signal(Deno.Signal.SIGUSR1).

  • userDefined2: () => SignalStream

    返回 SIGUSR2 信号流。

    Returns the stream of SIGUSR2 signals.

    此方法是 Deno.signal(Deno.Signal.SIGUSR2) 的简写形式。

    This method is the shorthand for Deno.signal(Deno.Signal.SIGUSR2).

  • windowChange: () => SignalStream

    返回 SIGWINCH 信号流。

    Returns the stream of SIGWINCH signals.

    此方法是 Deno.signal(Deno.Signal.SIGWINCH) 的简写形式。

    This method is the shorthand for Deno.signal(Deno.Signal.SIGWINCH).

Const stderr

stderr: File

用于 stderrDeno.File 实例。

An instance of Deno.File for stderr.

Const stdin

stdin: File

用于 stdinDeno.File 实例。

An instance of Deno.File for stdin.

Const stdout

stdout: File

用于 stdoutDeno.File 实例。

An instance of Deno.File for stdout.

Const symbols

symbols: { customInspect: keyof symbol; internal: keyof symbol }

不稳定: 新 API。可能会把 Deno.EOF 移动到这里。

UNSTABLE*: new API. Maybe move Deno.EOF here.

与 Deno 相关的 Symbol

Special Deno related symbols.

类型声明

  • Readonly customInspect: keyof symbol

    这个 Symbol 可以作为 key 来定义一个方法,当 Deno.inspect() 被调用或者调用了 console 的日志方法时,这个自定义函数被调用。

    A symbol which can be used as a key for a custom method which will be called when Deno.inspect() is called, or when the object is logged to the console.

  • Readonly internal: keyof symbol

    用于将 Deno 内部 API 暴露出来的 Symbol

    Symbol to access exposed internal Deno API

Const version

version: Version

Deno 的详细版本信息。包括了 deno、v8、typescript。

Version related information.

Functions

applySourceMap

  • 不稳定: 新 API,尚待审查。

    UNSTABLE: new API, yet to be vetted.

    给定模块中的当前位置,返回查找到的源文件中位置。

    Given a current location in a module, lookup the source location and return it.

    当 Deno 编译代码时,它将保留已编译代码的 source maps。 此功能可用于查找原始位置。 当访问 error 的 .stack 属性或出现未捕获的错误时,会自动执行此操作。 此功能可用于查找源文件以创建更好的错误处理。

    When Deno transpiles code, it keep source maps of the transpiled code. This function can be used to lookup the original location. This is automatically done when accessing the .stack of an error, or when an uncaught error is logged. This function can be used to perform the lookup for creating better error handling.

    注意: linecolumn 的下标从 1 开始,与代码的显示值匹配,但这种以 1 开始的索引方式并不代表 Deno 中大多数文件都是如此。

    Note: line and column are 1 indexed, which matches display expectations, but is not typical of most index numbers in Deno.

    示例:

    An example:

      const orig = Deno.applySourceMap({
        fileName: "file://my/module.ts",
        lineNumber: 5,
        columnNumber: 15
      });
      console.log(`${orig.filename}:${orig.line}:${orig.column}`);

    参数

    返回 Location

bundle

  • 不稳定:新的 API,尚待审核。

    UNSTABLE*: new API, yet to be vetted.

    bundle() 是编译器 API 的一部分。有关此功能的完整说明, 请参见 手册

    bundle() is part the compiler API. A full description of this functionality can be found in the manual.

    它接受根模块名 rootName,及可选参数 sources 做为模块源。 就像使用 deno bundle 命令输出的结果一样,其返回值是一个 JavaScript 字符串(如果在打包过程中出现错误, 则会返回错误诊断信息)。 如果仅传了 rootName,那么模块解析结果同命令行一致。

    Takes a root module name, and optionally a record set of sources. Resolves with a single JavaScript string (and bundle diagnostics if issues arise with the bundling) that is like the output of a deno bundle command. If just a root name is provided, the modules will be resolved as if the root module had been passed on the command line.

    如果传递了 sources,则所有模块都将从该 sources 对象中解析出来, 其中键是模块名称,值是内容。模块名称的扩展名将用于确定模块的类型。

    If sources are passed, all modules will be resolved out of this object, where the key is the module name and the value is the content. The extension of the module name will be used to determine the media type of the module.

     // 相当于执行 "deno bundle foo.ts" 命令
     const [ maybeDiagnostics1, output1 ] = await Deno.bundle("foo.ts");
     const [ maybeDiagnostics2, output2 ] = await Deno.bundle("/foo.ts", {
       "/foo.ts": `export * from "./bar.ts";`,
       "/bar.ts": `export const bar = "bar";`
     });

    参数

    • rootName: string

      作为 “起点” 的模块名。如果没有传递 sources 参数, Deno 将从外部解析模块,就像在命令行中指定了 rootName 一样。

      The root name of the module which will be used as the "starting point". If no sources is specified, Deno will resolve the module externally as if the rootName had been specified on the command line.

    • Optional sources: Record<string, string>

      可选参数,解析模块时使用的 key/value 对象,其中 key 是模块名,value 是源内容。 key 的扩展名决定了解析模块的类型。如果提供此参数,Deno 将不会尝试从外部解析任何模块。

      An optional key/value map of sources to be used when resolving modules, where the key is the module name, and the value is the source content. The extension of the key will determine the media type of the file when processing. If supplied, Deno will not attempt to resolve any modules externally.

    • Optional options: CompilerOptions

      编译选项。这是可以被 Deno 支持的 ts.CompilerOptions 选项的一个子集。

      An optional object of options to send to the compiler. This is a subset of ts.CompilerOptions which can be supported by Deno.

    返回 Promise<[DiagnosticItem[] | undefined, string]>

chdir

  • chdir(directory: string): void
  • 不稳定: 更改当前工作目录是否需要明确的权限,目前正在评估中。

    UNSTABLE: Currently under evaluation to decide if explicit permission is required to change the current working directory.

    将当前工作目录更改为指定路径。

    Change the current working directory to the specified path.

      Deno.chdir("/home/userA");
      Deno.chdir("../userB");
      Deno.chdir("C:\\Program Files (x86)\\Java");

    如果目录未被找到,则抛出 Deno.errors.NotFound 。 如果用户没有访问权限,则抛出 Deno.errors.PermissionDenied

    Throws Deno.errors.NotFound if directory not found. Throws Deno.errors.PermissionDenied if the user does not have access rights

    参数

    • directory: string

    返回 void

chmod

  • chmod(path: string, mode: number): Promise<void>
  • 更改指定路径下特定的文件/目录的权限。忽略进程的 umask。

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

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

    该模式是3个八进制数字的序列。 第一个/最左边的数字指定所有者(owner)的权限。 第二个数字指定组(group)的权限。 最后/最右边的数字指定其他用户的权限。 例如,在 0o764 模式下,所有者(owner)有读/写/执行权限(7),组(group)有读/写权限(6), 其他用户(4)只有读的权限。

    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.

    说明
    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

    注意:该 API 当前在 Windows 上使用会抛出异常。

    NOTE: This API currently throws on Windows

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

    • path: string
    • mode: number

    返回 Promise<void>

chmodSync

  • chmodSync(path: string, mode: number): void
  • 同步地更改指定路径下特定的文件/目录的权限。忽略进程的 umask。

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

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

    相关完整说明,参考 chmod

    For a full description, see chmod

    注意:该 API 当前在 Windows 上使用会抛出异常。

    NOTE: This API currently throws on Windows

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

    • path: string
    • mode: number

    返回 void

chown

  • chown(path: string, uid: number, gid: number): Promise<void>
  • 更改常规文件或目录的所有者。该功能在 Windows 上不可用。

    Change owner of a regular file or directory. This functionality is not available on Windows.

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

    需要 allow-write 权限。

    Requires allow-write permission.

    如果在 Windows 上执行,将抛出错误(未实现)。

    Throws Error (not implemented) if executed on Windows

    参数

    • path: string

      文件路径

      path to the file

    • uid: number

      user id (UID) of the new owner

      文件新的所有者的用户 ID (UID)

    • gid: number

      文件新的所有者的用户组 ID (GID)

      group id (GID) of the new owner

    返回 Promise<void>

chownSync

  • chownSync(path: string, uid: number, gid: number): void
  • 同步地更改常规文件或目录的所有者。该功能在 Windows 上不可用。

    Synchronously change owner of a regular file or directory. This functionality is not available on Windows.

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

    需要 allow-write 权限。

    Requires allow-write permission.

    如果在 Windows 上执行,将抛出错误(未实现)。

    Throws Error (not implemented) if executed on Windows

    参数

    • path: string

      文件路径

      path to the file

    • uid: number

      user id (UID) of the new owner

      文件新的所有者的用户 ID (UID)

    • gid: number

      文件新的所有者的用户组 ID (GID)

      group id (GID) of the new owner

    返回 void

close

  • close(rid: number): void
  • 使用给定的资源 ID (rid) 来关闭先前创建或打开的文件。 为避免资源泄露,事关重大,文件应当用完即关。

    Close the given resource ID (rid) which has been previously opened, such as via opening or creating a file. Closing a file when you are finished with it is important to avoid leaking resources.

     const file = await Deno.open("my_file.txt");
     // 与 "file" 对象一起使用
     Deno.close(file.rid);

    参数

    • rid: number

    返回 void

compile

  • compile(rootName: string, sources?: Record<string, string>, options?: CompilerOptions): Promise<[DiagnosticItem[] | undefined, Record<string, string>]>
  • 不稳定:新的 API,尚待审核。

    UNSTABLE*: new API, yet to be vetted.

    它接受根模块名 rootName,及 Record<string, string> 类型的可选参数 sources 做为模块源。返回编译后的模块集合及编译过程中遇到的问题的诊断信息。 如果仅传了 rootName,那么模块解析结果同命令行一致。

    Takes a root module name, and optionally a record set of sources. Resolves with a compiled set of modules and possibly diagnostics if the compiler encountered any issues. If just a root name is provided, the modules will be resolved as if the root module had been passed on the command line.

    如果传递了 sources,则所有模块都将从该 sources 对象中解析出来, 其中键是模块名称,值是内容。模块名称的扩展名将用于确定模块的类型。

    If sources are passed, all modules will be resolved out of this object, where the key is the module name and the value is the content. The extension of the module name will be used to determine the media type of the module.

     const [ maybeDiagnostics1, output1 ] = await Deno.compile("foo.ts");
     const [ maybeDiagnostics2, output2 ] = await Deno.compile("/foo.ts", {
       "/foo.ts": `export * from "./bar.ts";`,
       "/bar.ts": `export const bar = "bar";`
     });

    参数

    • rootName: string

      作为 “起点” 的模块名。如果没有传递 sources 参数, Deno 将从外部解析模块,就像在命令行中指定了 rootName 一样。

      The root name of the module which will be used as the "starting point". If no sources is specified, Deno will resolve the module externally as if the rootName had been specified on the command line.

    • Optional sources: Record<string, string>

      可选参数,解析模块时使用的 key/value 对象,其中 key 是模块名,value 是源内容。 key 的扩展名决定了解析模块的类型。如果提供此参数,Deno 将不会尝试从外部解析任何模块。

      An optional key/value map of sources to be used when resolving modules, where the key is the module name, and the value is the source content. The extension of the key will determine the media type of the file when processing. If supplied, Deno will not attempt to resolve any modules externally.

    • Optional options: CompilerOptions

      编译选项。这是可以被 Deno 支持的 ts.CompilerOptions 选项的一个子集。

      An optional object of options to send to the compiler. This is a subset of ts.CompilerOptions which can be supported by Deno.

    返回 Promise<[DiagnosticItem[] | undefined, Record<string, string>]>

connect

  • 通过指定传输协议(默认 "tcp")连接主机名(默认 "127.0.0.1")和端口号,并异步返回这个连接(Conn)。

    Connects to the hostname (default is "127.0.0.1") and port on the named transport (default is "tcp"), and resolves to the connection (Conn).

    const conn1 = await Deno.connect({ port: 80 });
    const conn2 = await Deno.connect({ hostname: "192.0.2.1", port: 80 });
    const conn3 = await Deno.connect({ hostname: "[2001:db8::1]", port: 80 });
    const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" });
    const conn5 = await Deno.connect({ address: "/foo/bar.sock", transport: "unix" });

    "tcp" 需要 allow-net 权限,unix 需要 allow-read 权限。

    Requires allow-net permission for "tcp" and allow-read for unix.

    参数

    返回 Promise<Conn>

connectTLS

  • 使用可选的证书文件、主机名(默认值为 "127.0.0.1") 和端口在 TLS(安全传输层协议)建立安全连接。 证书文件是可选的,如果不包含,则使用 Mozilla 的根证书 (具体参见 https://github.com/ctz/webpki-roots)。

    Establishes a secure connection over TLS (transport layer security) using an optional cert file, hostname (default is "127.0.0.1") and port. The cert file is optional and if not included Mozilla's root certificates will be used (see also https://github.com/ctz/webpki-roots for specifics)

    const conn1 = await Deno.connectTLS({ port: 80 });
    const conn2 = await Deno.connectTLS({ certFile: "./certs/my_custom_root_CA.pem", hostname: "192.0.2.1", port: 80 });
    const conn3 = await Deno.connectTLS({ hostname: "[2001:db8::1]", port: 80 });
    const conn4 = await Deno.connectTLS({ certFile: "./certs/my_custom_root_CA.pem", hostname: "golang.org", port: 80});

    需要 allow-net 权限。

    Requires allow-net permission.

    参数

    返回 Promise<Conn>

copy

  • src 拷贝文件至 dst,拷贝至 srcEOF 或有异常出现时结束。 copy() 函数返回一个 Promise, 成功时 resolve 并返回拷贝的字节数,失败时 reject 并返回拷贝过程中的首个异常。

    Copies from src to dst until either EOF is reached on src or an error occurs. It resolves to the number of bytes copied or rejects with the first error encountered while copying.

      const source = await Deno.open("my_file.txt");
      const buffer = new Deno.Buffer()
      const bytesCopied1 = await Deno.copy(Deno.stdout, source);
      const bytesCopied2 = await Deno.copy(buffer, source);

    因为 copy() 函数在读到 EOF 时停止,所以不会将 EOF 视为异常(区别于 read() 函数)。

    Because copy() is defined to read from src until EOF, it does not treat an EOF from read() as an error to be reported.

    参数

    • dst: Writer

      需要拷贝至的目标位置

      The destination to copy to

    • src: Reader

      拷贝的源位置

      The source to copy from

    返回 Promise<number>

copyFile

  • copyFile(fromPath: string, toPath: string): 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");

    fromPath 需要 allow-read 权限。 toPath 需要 allow-write 权限。

    Requires allow-read permission on fromPath. Requires allow-write permission on toPath.

    参数

    • fromPath: string
    • toPath: string

    返回 Promise<void>

copyFileSync

  • copyFileSync(fromPath: string, toPath: string): 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");

    fromPath 需要 allow-read 权限。 toPath 需要 allow-write 权限。

    Requires allow-read permission on fromPath. Requires allow-write permission on toPath.

    参数

    • fromPath: string
    • toPath: string

    返回 void

create

  • create(path: string): Promise<File>
  • 创建文件并异步返回一个 Deno.File 实例,如果文件已存在则进行覆盖。

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

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

    需要 allow-readallow-write 权限。

    Requires allow-read and allow-write permissions.

    参数

    • path: string

    返回 Promise<File>

createSync

  • createSync(path: string): File
  • 创建文件并返回一个 Deno.File 实例,如果文件已存在则进行覆盖。

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

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

    需要 allow-readallow-write 权限。

    Requires allow-read and allow-write permissions.

    参数

    • path: string

    返回 File

cwd

  • cwd(): string
  • 不稳定: 获取当前工作目录是否需要明确的权限,目前正在评估中。

    UNSTABLE: Currently under evaluation to decide if explicit permission is required to get the value of the current working directory.

    返回当前工作目录的字符串。

    Return a string representing the current working directory.

    如果当前目录可以通过多个路径访问(由于符号链接导致),可能会返回其中任意一个。

    If the current directory can be reached via multiple paths (due to symbolic links), cwd() may return any one of them.

      const currentWorkingDirectory = Deno.cwd();

    如果目录不存在,则抛出 Deno.errors.NotFound

    Throws Deno.errors.NotFound if directory not available.

    返回 string

dir

  • dir(kind: DirKind): string | null
  • 不稳定: 当前正在评估中,以确定是否应重命名方法名 dir 和参数类型 DirKind

    UNSTABLE: Currently under evaluation to decide if method name dir and parameter type alias name DirKind should be renamed.

    返回特定于用户和平台的目录。

    Returns the user and platform specific directories.

      const homeDirectory = Deno.dir("home");

    需要 allow-env 权限。

    Requires allow-env permission.

    如果没有适用的目录或发生任何其他错误,则返回 null

    Returns null if there is no applicable directory or if any other error occurs.

    参数值包含:"home", "cache", "config", "executable", "data", "data_local", "audio", "desktop", "document", "download", "font", "picture", "public", "template", "tmp", "video"

    Argument values: "home", "cache", "config", "executable", "data", "data_local", "audio", "desktop", "document", "download", "font", "picture", "public", "template", "tmp", "video"

    "home"

    平台 示例
    Linux $HOME /home/alice
    macOS $HOME /Users/alice
    Windows {FOLDERID_Profile} C:\Users\Alice

    "cache"

    平台 示例
    Linux $XDG_CACHE_HOME or $HOME/.cache /home/alice/.cache
    macOS $HOME/Library/Caches /Users/Alice/Library/Caches
    Windows {FOLDERID_LocalAppData} C:\Users\Alice\AppData\Local

    "config"

    平台 示例
    Linux $XDG_CONFIG_HOME or $HOME/.config /home/alice/.config
    macOS $HOME/Library/Preferences /Users/Alice/Library/Preferences
    Windows {FOLDERID_RoamingAppData} C:\Users\Alice\AppData\Roaming

    "executable"

    平台 示例
    Linux XDG_BIN_HOME or $XDG_DATA_HOME/../bin or $HOME/.local/bin /home/alice/.local/bin
    macOS - -
    Windows - -

    "data"

    平台 示例
    Linux $XDG_DATA_HOME or $HOME/.local/share /home/alice/.local/share
    macOS $HOME/Library/Application Support /Users/Alice/Library/Application Support
    Windows {FOLDERID_RoamingAppData} C:\Users\Alice\AppData\Roaming

    "data_local"

    平台 示例
    Linux $XDG_DATA_HOME or $HOME/.local/share /home/alice/.local/share
    macOS $HOME/Library/Application Support /Users/Alice/Library/Application Support
    Windows {FOLDERID_LocalAppData} C:\Users\Alice\AppData\Local

    "audio"

    平台 示例
    Linux XDG_MUSIC_DIR /home/alice/Music
    macOS $HOME/Music /Users/Alice/Music
    Windows {FOLDERID_Music} C:\Users\Alice\Music

    "desktop"

    平台 示例
    Linux XDG_DESKTOP_DIR /home/alice/Desktop
    macOS $HOME/Desktop /Users/Alice/Desktop
    Windows {FOLDERID_Desktop} C:\Users\Alice\Desktop

    "document"

    平台 示例
    Linux XDG_DOCUMENTS_DIR /home/alice/Documents
    macOS $HOME/Documents /Users/Alice/Documents
    Windows {FOLDERID_Documents} C:\Users\Alice\Documents

    "download"

    平台 示例
    Linux XDG_DOWNLOAD_DIR /home/alice/Downloads
    macOS $HOME/Downloads /Users/Alice/Downloads
    Windows {FOLDERID_Downloads} C:\Users\Alice\Downloads

    "font"

    平台 示例
    Linux $XDG_DATA_HOME/fonts or $HOME/.local/share/fonts /home/alice/.local/share/fonts
    macOS $HOME/Library/Fonts /Users/Alice/Library/Fonts
    Windows

    "picture"

    平台 示例
    Linux XDG_PICTURES_DIR /home/alice/Pictures
    macOS $HOME/Pictures /Users/Alice/Pictures
    Windows {FOLDERID_Pictures} C:\Users\Alice\Pictures

    "public"

    平台 示例
    Linux XDG_PUBLICSHARE_DIR /home/alice/Public
    macOS $HOME/Public /Users/Alice/Public
    Windows {FOLDERID_Public} C:\Users\Public

    "template"

    平台 示例
    Linux XDG_TEMPLATES_DIR /home/alice/Templates
    macOS
    Windows {FOLDERID_Templates} C:\Users\Alice\AppData\Roaming\Microsoft\Windows\Templates

    "tmp"

    平台 示例
    Linux TMPDIR /tmp
    macOS TMPDIR /tmp
    Windows {TMP} C:\Users\Alice\AppData\Local\Temp

    "video"

    平台 示例
    Linux XDG_VIDEOS_DIR /home/alice/Videos
    macOS $HOME/Movies /Users/Alice/Movies
    Windows {FOLDERID_Videos} C:\Users\Alice\Videos

    参数

    返回 string | null

env

  • env(): {}
  • env(key: string): string | undefined
  • 返回调用时环境变量的快照。如果更改环境变量对象的属性,则会在进程的环境中设置该属性。 环境变量对象只接受 string 类型的值。

    Returns a snapshot of the environment variables at invocation. Changing a property in the object will set that variable in the environment for the process. The environment object will only accept strings as values.

      const myEnv = Deno.env();
      console.log(myEnv.SHELL);
      myEnv.TEST_VAR = "HELLO";
      const newEnv = Deno.env();
      console.log(myEnv.TEST_VAR === newEnv.TEST_VAR);  //outputs "true"

    需要 allow-env 权限。

    Requires allow-env permission.

    返回 {}

    • [index: string]: string
  • 获取环境变量的值。如果 key 不存在,则返回 undefined

    Retrieve the value of an environment variable. Returns undefined if that key doesn't exist.

      console.log(Deno.env("HOME"));  //e.g. outputs "/home/alice"
      console.log(Deno.env("MADE_UP_VAR"));  //outputs "Undefined"

    需要 allow-env 权限。

    Requires allow-env permission.

    参数

    • key: string

    返回 string | undefined

execPath

  • execPath(): string
  • 返回当前 deno 可执行文件的路径。

    Returns the path to the current deno executable.

      console.log(Deno.execPath());  //e.g. "/home/alice/.local/bin/deno"

    需要 allow-env 权限。

    Requires allow-env permission.

    返回 string

exit

  • exit(code?: number): never
  • 退出 Deno 进程,可以指定退出码,若无则为 0。

    Exit the Deno process with optional exit code. If no exit code is supplied then Deno will exit with return code of 0.

      Deno.exit(5);

    参数

    • Optional code: number

    返回 never

formatDiagnostics

  • 不稳定: 新 API,没有经过审查。

    UNSTABLE*: new API, yet to be vetted.

    格式化诊断信息数组,并以用户友好的格式将其作为单个字符串返回。

    Format an array of diagnostic items and return them as a single string in a user friendly format.

      const [diagnostics, result] = Deno.compile("file_with_compile_issues.ts");
      console.table(diagnostics);  // 输出原始诊断信息
      console.log(Deno.formatDiagnostics(diagnostics));  // 用户友好方式的输出诊断信息

    参数

    • items: DiagnosticItem[]

      要格式化的诊断信息数组

      An array of diagnostic items to format

    返回 string

fsEvents

  • fsEvents(paths: string | string[], options?: { recursive: boolean }): AsyncIterableIterator<FsEvent>
  • 不稳定: 新 API,没有经过审查。

    UNSTABLE*: new API, yet to be vetted.

    监听一个或多个路径的文件系统事件,这个路径可以是文件或者目录,但是必须存在。 一个用户操作(例如 touch test.file)可以产生多个文件系统事件。同样,一个 用户操作也可能在一次事件中影响多个路径(例如 mv old_name.txt new_name.txt)。 递归选项默认为 true,对于目录,将监听指定目录及其所有子目录。 值得注意的是,不同操作系统的事件顺序可能会有所不同。

    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). 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 iter = Deno.fsEvents("/");
      for await (const event of iter) {
         console.log(">>>> event", event);  //e.g. { kind: "create", paths: [ "/foo.txt" ] }
      }

    需要 allow-read 权限。

    Requires allow-read permission.

    参数

    • paths: string | string[]
    • Optional options: { recursive: boolean }
      • recursive: boolean

    返回 AsyncIterableIterator<FsEvent>

hostname

  • hostname(): string
  • 获取 Deno 进程所在的计算机主机名(hostname)。

    Get the hostname of the machine the Deno process is running on.

      console.log(Deno.hostname());

    需要 allow-env 权限。

    Requires allow-env permission.

    返回 string

inspect

  • 不稳定:字符串输出的确切形式仍在考虑,可能会更改。

    UNSTABLE*: The exact form of the string output is under consideration and may change.

    将输入转换为与 console.log() 打印格式相同的字符串。

    Converts the input into a string that has the same format as printed by console.log().

     const obj = {};
     obj.propA = 10;
     obj.propB = "hello"
     const objAsString = Deno.inspect(obj); //{ propA: 10, propB: "hello" }
     console.log(obj);  // 输出与 objAsString 相同的值,例如: { propA: 10, propB: "hello" }

    你还可以通过对象上的 Deno.symbols.customInspect 函数 注册自定义的 inspect function,以控制和自定义输出。

    You can also register custom inspect functions, via the customInspect Deno symbol on objects, to control and customize the output.

     class A {
       x = 10;
       y = "hello";
       [Deno.symbols.customInspect](): string {
         return "x=" + this.x + ", y=" + this.y;
       }
     }
     const inStringFormat = Deno.inspect(new A()); //"x=10, y=hello"
     console.log(inStringFormat);  // 输出 "x=10, y=hello"

    同时还提供了一些输出选项。

    Finally, a number of output options are also available.

     const out = Deno.inspect(obj, {showHidden: true, depth: 4, colors: true, indentLevel: 2});

    参数

    返回 string

isatty

  • isatty(rid: number): boolean
  • 不稳定: 新 API,没有经过审查。

    UNSTABLE*: new API, yet to be vetted

    检查指定的资源 id (rid) 是否为 TTY(终端)。

    Check if a given resource id (rid) is a TTY.

      // 这个例子依赖于特定的操作系统和环境
      const nonTTYRid = Deno.openSync("my_file.txt").rid;
      const ttyRid = Deno.openSync("/dev/tty6").rid;
      console.log(Deno.isatty(nonTTYRid)); // false
      console.log(Deno.isatty(ttyRid)); // true
      Deno.close(nonTTYRid);
      Deno.close(ttyRid);

    参数

    • rid: number

    返回 boolean

kill

  • kill(pid: number, signo: number): void
  • UNSTABLE: signo 参数可能需要改成 Deno.Signal 枚举。

    UNSTABLE*: The signo argument may change to require the Deno.Signal enum.

    给指定的 pid 进程发送信号。这个功能目前只在 Linux 和 Mac OS 上运行。

    Send a signal to process under given pid. This functionality currently only works on Linux and Mac OS.

    pid 是负的,信号将会发送到带有 pid 标识的进程组。

    If pid is negative, the signal will be sent to the process group identified by pid.

     const p = Deno.run({
       cmd: ["python", "-c", "from time import sleep; sleep(10000)"]
     });
     Deno.kill(p.pid, Deno.Signal.SIGINT);

    在 Windows 上抛出错误(尚未实现)。

    Throws Error (not yet implemented) on Windows

    需要 allow-run 权限。

    Requires allow-run permission.

    参数

    • pid: number
    • signo: number

    返回 void

link

  • link(oldpath: string, newpath: string): Promise<void>
  • 创建 newpath 作为 oldpath 的硬链接。

    Creates newpath as a hard link to oldpath.

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

    需要 allow-readallow-write 权限。

    Requires allow-read and allow-write permissions.

    参数

    • oldpath: string
    • newpath: string

    返回 Promise<void>

linkSync

  • linkSync(oldpath: string, newpath: string): void
  • 同步方式创建 newpath 作为 oldpath 的硬链接。

    Synchronously creates newpath as a hard link to oldpath.

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

    需要 allow-readallow-write 权限。

    Requires allow-read and allow-write permissions.

    参数

    • oldpath: string
    • newpath: string

    返回 void

listen

  • 不稳定: 新 API,没有经过审查。

    UNSTABLE*: new API, yet to be vetted.

    在本地监听网络连接。

    Listen announces on the local transport address.

     const listener1 = Deno.listen({ port: 80 })
     const listener2 = Deno.listen({ hostname: "192.0.2.1", port: 80 })
     const listener3 = Deno.listen({ hostname: "[2001:db8::1]", port: 80 });
     const listener4 = Deno.listen({ hostname: "golang.org", port: 80, transport: "tcp" });

    需要 allow-net 权限。

    Requires allow-net permission.

    参数

    返回 Listener

  • 不稳定: 新 API,没有经过审查。

    UNSTABLE*: new API, yet to be vetted.

    在本地监听网络连接。

    Listen announces on the local transport address.

    const listener = Deno.listen({ address: "/foo/bar.sock", transport: "unix" })

    需要 allow-read 权限。

    Requires allow-read permission.

    参数

    返回 Listener

  • 不稳定: 新 API,没有经过审查。

    UNSTABLE*: new API, yet to be vetted.

    在本地监听网络连接。

    Listen announces on the local transport address.

     const listener1 = Deno.listen({ port: 80, transport: "udp" })
     const listener2 = Deno.listen({ hostname: "golang.org", port: 80, transport: "udp" });

    需要 allow-net 权限。

    Requires allow-net permission.

    参数

    返回 DatagramConn

  • 不稳定: 新 API,没有经过审查。

    UNSTABLE*: new API, yet to be vetted.

    在本地监听网络连接。

    Listen announces on the local transport address.

    const listener = Deno.listen({ address: "/foo/bar.sock", transport: "unixpacket" })

    需要 allow-read 权限。

    Requires allow-read permission.

    参数

    返回 DatagramConn

listenTLS

  • 在本地监听来自 TLS (传输层安全性协议)的网络连接。

    Listen announces on the local transport address over TLS (transport layer security).

     const lstnr = Deno.listenTLS({ port: 443, certFile: "./server.crt", keyFile: "./server.key" });

    需要 allow-net 权限。

    Requires allow-net permission.

    参数

    返回 Listener

loadavg

  • loadavg(): number[]
  • 返回 1 分钟、5 分钟和 15 分钟平均负载的数组。 平均负载是对最后 1 分钟、5 分钟和 15 分钟的 CPU 以及 IO 利用率的度量,以分数表示。 0 表示没有负载。 在 Windows 上,这 3 个值始终相同,代表当前负载,而不是 1 分钟、5 分钟和 15 分钟的平均负载。

    Returns an array containing the 1, 5, and 15 minute load averages. The load average is a measure of CPU and IO utilization of the last one, five, and 15 minute periods expressed as a fractional number. Zero means there is no load. On Windows, the three values are always the same and represent the current load, not the 1, 5 and 15 minute load averages.

      console.log(Deno.loadavg());  //e.g. [ 0.71, 0.44, 0.44 ]

    需要 allow-env 权限。

    Requires allow-env permission.

    返回 number[]

lstat

  • lstat(path: string): Promise<FileInfo>
  • 解析给定的 path,并返回 Deno.FileInfo。如果 path 是一个 符号链接,则将返回符号链接的信息,而不是该符号链接引用的文件信息。

    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.

      const fileInfo = await Deno.lstat("hello.txt");
      assert(fileInfo.isFile);

    需要 allow-read 权限。

    Requires allow-read permission.

    参数

    • path: string

    返回 Promise<FileInfo>

lstatSync

  • 同步方式解析给定的 path,并返回 Deno.FileInfo。如果 path 是一个 符号链接,则将返回符号链接的信息,而不是该符号链接引用的文件信息。

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

      const fileInfo = Deno.lstatSync("hello.txt");
      assert(fileInfo.isFile);

    需要 allow-read 权限。

    Requires allow-read permission.

    参数

    • path: string

    返回 FileInfo

makeTempDir

  • 在默认文件夹(另见 Deno.dir("temp"))中创建一个临时文件夹, 如果指定了 dir , 则在指定的 dir 中创建。 其他可选的参数包括分别给文件夹名添加前缀的 prefix 和给文件夹名添加后缀的 sufix

    Creates a new temporary directory in the default directory for temporary files (see also Deno.dir("temp")), 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

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

    返回 Promise<string>

makeTempDirSync

  • 以同步的方式在默认文件夹(另见 Deno.dir("temp"))中创建一个临时文件夹, 如果指定了 dir , 则在指定的 dir 中创建。 其他可选的参数包括分别给文件夹名添加前缀的 prefix 和给文件夹名添加后缀的 sufix

    Synchronously creates a new temporary directory in the default directory for temporary files (see also Deno.dir("temp")), 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

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

    返回 string

makeTempFile

  • 在默认文件夹(另见 Deno.dir("temp"))中创建一个临时文件, 如果指定了 dir , 则在指定的 dir 中创建。 其他可选的参数包括分别给文件名添加前缀的 prefix 和给文件名添加后缀的 sufix

    Creates a new temporary file in the default directory for temporary files (see also Deno.dir("temp")), 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 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

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

    返回 Promise<string>

makeTempFileSync

  • 以同步的方式在默认文件夹(另见 Deno.dir("temp"))中创建一个临时文件, 如果指定了 dir , 则在指定的 dir 中创建。 其他可选的参数包括分别给文件名添加前缀的 prefix 和给文件名添加后缀的 sufix

    Synchronously creates a new temporary file in the default directory for temporary files (see also Deno.dir("temp")), 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 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

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

    返回 string

metrics

  • 从 Deno 的特权方接收指标。这主要用于 Deno 的开发中。 'Ops'(也称为 'bindings')是 Deno Javascript 和 Deno Rust 之间的沟通桥梁。

    Receive metrics from the privileged side of Deno. This is primarily used in the development of Deno. 'Ops', also called 'bindings', are the go-between between Deno Javascript and Deno Rust.

     > console.table(Deno.metrics())
     ┌─────────────────────────┬────────┐
     │         (index)         │ Values │
     ├─────────────────────────┼────────┤
     │      opsDispatched      │   3    │
     │    opsDispatchedSync    │   2    │
     │   opsDispatchedAsync    │   1    │
     │ opsDispatchedAsyncUnref │   0    │
     │      opsCompleted       │   3    │
     │    opsCompletedSync     │   2    │
     │    opsCompletedAsync    │   1    │
     │ opsCompletedAsyncUnref  │   0    │
     │    bytesSentControl     │   73   │
     │      bytesSentData      │   0    │
     │      bytesReceived      │  375   │
     └─────────────────────────┴────────┘

    返回 Metrics

mkdir

  • mkdir(path: string, 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 });

    目录存在的情况下,默认抛出错误。

    Defaults to throwing error if the directory already exists.

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

    返回 Promise<void>

mkdirSync

  • 同步地在指定路径下创建一个新的目录。

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

    目录存在的情况下,默认抛出错误。

    Defaults to throwing error if the directory already exists.

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

    返回 void

open

  • 打开一个文件并异步返回一个 Deno.File 实例。如果使用了 createcreateNew配置项 文件可以不需要预先存在。调用者应该在完成后关闭文件。

    Open a file and resolve to an instance of Deno.File. The file does not need to previously exist if using the create or createNew open options. It is the callers responsibility to close the file when finished with it.

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

    根据不同的选项需要相应的 allow-readallow-write 权限。

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

    参数

    返回 Promise<File>

  • 打开一个文件并异步返回一个 Deno.File 实例。根据传入的模式,可以创建文件。 调用者应该在完成后关闭文件。

    Open a file and resolve to an instance of Deno.File. The file may be created depending on the mode passed in. It is the callers responsibility to close the file when finished with it.

      const file = await Deno.open("/foo/bar.txt", "w+");
      // Do work with file
      Deno.close(file.rid);

    根据不同的打开模式需要相应的 allow-readallow-write 权限。

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

    参数

    • path: string
    • Optional openMode: OpenMode

    返回 Promise<File>

openPlugin

  • openPlugin(filename: string): Plugin
  • 不稳定: 新 API,没有经过审查。

    UNSTABLE*: new API, yet to be vetted.

    打开并初始化插件。

    Open and initalize a plugin.

       const plugin = Deno.openPlugin("./path/to/some/plugin.so");
       const some_op = plugin.ops.some_op;
       const response = some_op.dispatch(new Uint8Array([1,2,3,4]));
       console.log(`Response from plugin ${response}`);

    需要 allow-plugin 权限。

    Requires allow-plugin permission.

    参数

    • filename: string

    返回 Plugin

openSync

  • 用同步方式打开一个文件并返回一个 Deno.File 实例。如果使用了 createcreateNew配置项 文件可以不需要预先存在。调用者应该在完成后关闭文件。

    Synchronously open a file and return an instance of Deno.File. The file does not need to previously exist if using the create or createNew open options. It is the callers responsibility to close the file when finished with it.

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

    根据不同的配置需要相应的 allow-readallow-write 权限。

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

    参数

    返回 File

  • 用同步方式打开一个文件并返回一个 Deno.File 实例。根据传入的模式,可以创建文件。 调用者应该在完成后关闭文件。

    Synchronously open a file and return an instance of Deno.File. The file may be created depending on the mode passed in. It is the callers responsibility to close the file when finished with it.

      const file = Deno.openSync("/foo/bar.txt", "r");
      // Do work with file
      Deno.close(file.rid);

    根据不同的打开模式需要相应的 allow-readallow-write 权限。

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

    参数

    • path: string
    • Optional openMode: OpenMode

    返回 File

osRelease

  • osRelease(): string
  • 返回操作系统的发行版本。

    Returns the release version of the Operating System.

      console.log(Deno.osRelease());

    需要 allow-env 权限。

    Requires allow-env permission.

    返回 string

read

  • read(rid: number, buffer: Uint8Array): Promise<number | unique symbol>
  • 从资源ID (rid) 读取内容,并写入到数组缓冲区 (buffer)。

    Read from a resource ID (rid) into an array buffer (buffer).

    如果没有要读取的内容,返回值为操作期间读取的字节数,或者文件结尾(Symbol(EOF))。

    Resolves to either the number of bytes read during the operation or End Of File (Symbol(EOF)) if there was nothing to read.

     // 如果 "/foo/bar.txt" 文件里面有 "hello world":
     const file = await Deno.open("/foo/bar.txt");
     const buf = new Uint8Array(100);
     const numberOfBytesRead = await Deno.read(file.rid, buf); // 11 bytes
     const text = new TextDecoder().decode(buf);  // "hello world"
     Deno.close(file.rid);

    参数

    • rid: number
    • buffer: Uint8Array

    返回 Promise<number | unique symbol>

readAll

  • readAll(r: Reader): Promise<Uint8Array>
  • 读取 Reader r 直到文件的末尾 (Deno.EOF),返回文件的内容,以 Uint8Array 表示。

    Read Reader r until end of file (Deno.EOF) and resolve to the content as Uint8Array.

      // Example:从 stdin 读取
      const stdinContent = await Deno.readAll(Deno.stdin);
      // Example:从文件读取
      const file = await Deno.open("my_file.txt", {read: true});
      const myFileContent = await Deno.readAll(file);
      Deno.close(file.rid);
      // Example:从 buffer 读取
      const myData = new Uint8Array(100);
      // ... 此处省略了填充 myData 数组的代码
      const reader = new Deno.Buffer(myData.buffer as ArrayBuffer);
      const bufferContent = await Deno.readAll(reader);

    参数

    返回 Promise<Uint8Array>

readAllSync

  • 同步地读取 Reader r 直到文件的末尾 (Deno.EOF),返回文件的内容,以 Uint8Array 表示。

    Synchronously reads Reader r until end of file (Deno.EOF) and returns the content as Uint8Array.

      // Example:从 stdin 读取
      const stdinContent = Deno.readAllSync(Deno.stdin);
      // Example:从文件读取
      const file = Deno.openSync("my_file.txt", {read: true});
      const myFileContent = Deno.readAllSync(file);
      Deno.close(file.rid);
      // Example:从 buffer 读取
      const myData = new Uint8Array(100);
      //... 此处省略了填充 myData 数组的代码
      const reader = new Deno.Buffer(myData.buffer as ArrayBuffer);
      const bufferContent = Deno.readAllSync(reader);

    参数

    返回 Uint8Array

readFile

  • readFile(path: string): Promise<Uint8Array>
  • 读取并将文件的全部内容解析为字节数组。 TextDecoder 可以在需要的情况下可以将字节转换成字符串。 读取目录返回一个空的数据数组。

    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. Reading a directory returns an empty data array.

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

    需要 allow-read 权限。

    Requires allow-read permission.

    参数

    • path: string

    返回 Promise<Uint8Array>

readFileSync

  • readFileSync(path: string): Uint8Array
  • 同步地读取并将文件的全部内容解析为字节数组。 TextDecoder 可以在需要的情况下可以将字节转换成字符串。 读取目录返回一个空的数据数组。

    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. Reading a directory returns an empty data array.

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

    需要 allow-read 权限。

    Requires allow-read permission.

    参数

    • path: string

    返回 Uint8Array

readLink

  • readLink(path: string): 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"); // ./test.txt 的绝对路径

    如果使用硬链接调用,则会抛出 TypeError

    Throws TypeError if called with a hard link

    需要 allow-read 权限。

    Requires allow-read permission.

    参数

    • path: string

    返回 Promise<string>

readLinkSync

  • readLinkSync(path: string): string
  • 同步方式解析并返回符号链接对目标文件的绝对路径。

    Returns the full path destination of the named symbolic link.

      Deno.symlinkSync("./test.txt", "./test_link.txt");
      const target = Deno.readLinkSync("./test_link.txt"); // ./test.txt 的绝对路径

    如果使用硬链接调用,则会抛出 TypeError

    Throws TypeError if called with a hard link

    需要 allow-read 权限。

    Requires allow-read permission.

    参数

    • path: string

    返回 string

readSync

  • readSync(rid: number, buffer: Uint8Array): number | unique symbol
  • 同步地从资源ID (rid) 读取内容,并写入到数组缓冲区 (buffer)。

    Synchronously read from a resource ID (rid) into an array buffer (buffer).

    如果没有要读取的内容,返回值为操作期间读取的字节数,或者文件结尾(Symbol(EOF))。

    Returns either the number of bytes read during the operation or End Of File (Symbol(EOF)) if there was nothing to read.

     // 如果 "/foo/bar.txt" 文件里面有 "hello world":
     const file = Deno.openSync("/foo/bar.txt");
     const buf = new Uint8Array(100);
     const numberOfBytesRead = Deno.readSync(file.rid, buf); // 11 bytes
     const text = new TextDecoder().decode(buf);  // "hello world"
     Deno.close(file.rid);

    参数

    • rid: number
    • buffer: Uint8Array

    返回 number | unique symbol

readdir

  • readdir(path: string): AsyncIterable<DirEntry>
  • 读取 path 文件目录,并返回 Deno.DirEntry 迭代器。

    Reads the directory given by path and returns an async iterable of Deno.DirEntry.

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

    如果 path 不是目录则抛出错误。

    Throws error if path is not a directory.

    Requires allow-read permission.

    参数

    • path: string

    返回 AsyncIterable<DirEntry>

readdirSync

  • readdirSync(path: string): Iterable<DirEntry>
  • 同步读取 path 文件目录,并返回 Deno.DirEntry 迭代器。

    Synchronously reads the directory given by path and returns an iterable of Deno.DirEntry.

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

    如果 path 不是目录则抛出错误。

    Throws error if path is not a directory.

    需要 allow-read 权限。

    Requires allow-read permission.

    参数

    • path: string

    返回 Iterable<DirEntry>

realpath

  • realpath(path: string): 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"

    需要 allow-read 权限

    Requires allow-read permission.

    参数

    • path: string

    返回 Promise<string>

realpathSync

  • realpathSync(path: string): string
  • 返回被解析后的符号链接绝对路径。

    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"

    需要 allow-read 权限。

    Requires allow-read permission.

    参数

    • path: string

    返回 string

remove

  • 删除指定的文件或目录。

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

    当权限被拒绝、路径找不到或者为非空目录且 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.

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

    返回 Promise<void>

removeSync

  • 同步删除指定的文件或目录。

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

    当权限被拒绝、路径找不到或者为非空目录且 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.

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

    返回 void

rename

  • rename(oldpath: string, newpath: string): Promise<void>
  • oldpath 重命名(或移动)为 newpath。路径可以是文件或目录。 如果 newpath 已经存在且不是目录,那么 rename() 将替换它。 当 oldpathnewpath 位于不同的目录中时,可能会受到操作系统的限制。

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

    在 Unix 系统上,此操作不会修改符号链接所指向的内容。

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

    当操作引发错误时,平台之间会有所不同。 如果 newpath 是非空目录则始终会报错。

    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.

    需要 allow-readallow-write 权限。

    Requires allow-read and allow-write permission.

    参数

    • oldpath: string
    • newpath: string

    返回 Promise<void>

renameSync

  • renameSync(oldpath: string, newpath: string): void
  • 同步方式将 oldpath 重命名(或移动)为 newpath。路径可以是文件或目录。 如果 newpath 已经存在且不是目录,那么 rename() 将替换它。 当 oldpathnewpath 位于不同的目录中时,可能会受到操作系统的限制。

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

    在 Unix 系统上,此操作不会修改符号链接所指向的内容。

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

    当操作引发错误时,平台之间会有所不同。 如果 newpath 是非空目录则始终会报错。

    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.

    需要 allow-readallow-write 权限。

    Requires allow-read and allow-write permissions.

    参数

    • oldpath: string
    • newpath: string

    返回 void

resources

  • 不稳定: 返回类型正在考虑中,并且可能会更改。

    UNSTABLE*: The return type is under consideration and may change.

    返回打开的_文件_资源 ID(rid)及其字符串表示形式的 Map。

    Returns a map of open file like resource ids (rid) along with their string representations.

      console.log(Deno.resources()); //e.g. { 0: "stdin", 1: "stdout", 2: "stderr" }
      Deno.openSync('../test.file');
      console.log(Deno.resources()); //e.g. { 0: "stdin", 1: "stdout", 2: "stderr", 3: "fsFile" }

    返回 ResourceMap

run

  • 派生新的子进程。 RunOptions 必须包含 opt.cmd,即程序参数数组,其中第一个参数是二进制文件路径。

    Spawns new subprocess. RunOptions must contain at a minimum the opt.cmd, an array of program arguments, the first of which is the binary.

    子进程使用与父进程相同的工作目录,除非指定了 opt.cwd

    Subprocess uses same working directory as parent process unless opt.cwd is specified.

    子进程的环境变量可以使用 opt.env 来设置。

    Environmental variables for subprocess can be specified using opt.env mapping.

    默认情况下,子进程继承父进程的 stdio。要更改这些值,可以分别指定opt.stdoutopt.stderropt.stdin

    • 可以将其设置为 ProcessStdio 或打开文件的 rid

    By default subprocess inherits stdio of parent process. To change that opt.stdout, opt.stderr and opt.stdin can be specified independently - they can be set to either ProcessStdio or rid of open file.

    返回派生子进程的详细信息。

    Details of the spawned process are returned.

      const p = Deno.run({
        cmd: ["echo", "hello"],
      });

    需要 allow-run 权限。

    Requires allow-run permission.

    参数

    返回 Process

runTests

  • 运行所有通过 Deno.test() 注册的测试。始终异步 resolve。

    Run any tests which have been registered via Deno.test(). Always resolves asynchronously.

       // 注册一个测试。
       Deno.test({
         name: "example test",
         fn(): void {
           assertEquals("world", "world");
           assertEquals({ hello: "world" }, { hello: "world" });
         },
       });
       // 运行所有已经注册过的测试。
       const runInfo = await Deno.runTests();
       console.log(runInfo.duration);  // all tests duration, e.g. "5" (in ms)
       console.log(runInfo.stats.passed);  //e.g. 1
       console.log(runInfo.results[0].name);  //e.g. "example test"

    参数

    返回 Promise<TestMessage["end"]> & {}

seek

  • seek(rid: number, offset: number, whence: SeekMode): Promise<number>
  • 在给定查询模式 whence 和偏移量 offset 的情况下,查找指定的资源 ID(rid)。 函数将解析并返回光标在资源中的新位置(从头开始的字节数)。

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

       const file = await Deno.open('hello.txt', {read: true, write: true, truncate: true, create: true});
       await Deno.write(file.rid, new TextEncoder().encode("Hello world"));
       // 光标前进 6 个字节
       const cursorPosition = await Deno.seek(file.rid, 6, Deno.SeekMode.SEEK_START);
       console.log(cursorPosition);  // 6
       const buf = new Uint8Array(100);
       await file.read(buf);
       console.log(new TextDecoder().decode(buf)); // "world"

    seek modes 的工作方式如下:

    The seek modes work as follows:

       // 给定内容为 "Hello world" 的 file.rid 文件,该文件长度为 11 个字节。
       // 从文件开头移动 6 个字节
       console.log(await Deno.seek(file.rid, 6, Deno.SeekMode.SEEK_START)); //"6"
       // 从当前位置再移动 2 个字节
       console.log(await Deno.seek(file.rid, 2, Deno.SeekMode.SEEK_CURRENT)); //"8"
       // 从文件末尾向后移动 2 个字节
       console.log(await Deno.seek(file.rid, -2, Deno.SeekMode.SEEK_END)); //"9" (e.g. 11-2)

    参数

    • rid: number
    • offset: number
    • whence: SeekMode

    返回 Promise<number>

seekSync

  • seekSync(rid: number, offset: number, whence: SeekMode): number
  • 同步方式,在给定查询模式 whence 和偏移量 offset 的情况下,查找指定的资源 ID(rid)。 函数将解析并返回光标在资源中的新位置(从头开始的字节数)。

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

       const file = Deno.openSync('hello.txt', {read: true, write: true, truncate: true, create: true});
       Deno.writeSync(file.rid, new TextEncoder().encode("Hello world"));
       //advance cursor 6 bytes
       const cursorPosition = Deno.seekSync(file.rid, 6, Deno.SeekMode.SEEK_START);
       console.log(cursorPosition);  // 6
       const buf = new Uint8Array(100);
       file.readSync(buf);
       console.log(new TextDecoder().decode(buf)); // "world"

    seek modes 的工作方式如下:

    The seek modes work as follows:

       // 给定内容为 "Hello world" 的 file.rid 文件,该文件长度为 11 个字节。
       // 从文件开头移动 6 个字节
       console.log(Deno.seekSync(file.rid, 6, Deno.SeekMode.SEEK_START)); //"6"
       // 从当前位置再移动 2 个字节
       console.log(Deno.seekSync(file.rid, 2, Deno.SeekMode.SEEK_CURRENT)); //"8"
       // 从文件末尾向后移动 2 个字节
       console.log(Deno.seekSync(file.rid, -2, Deno.SeekMode.SEEK_END)); //"9" (e.g. 11-2)

    参数

    • rid: number
    • offset: number
    • whence: SeekMode

    返回 number

setRaw

  • setRaw(rid: number, mode: boolean): void
  • 不稳定: 新 API,没有经过审查。

    UNSTABLE*: new API, yet to be vetted

    设置终端是否为 raw 模式。 在 raw 模式下,无需处理即可直接读取和返回字符。 终端将禁止所有特殊的字符处理,包括回显输入字符。 在 raw 模式下从终端设备读取的速度比在标准模式下更快。

    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.

      Deno.setRaw(myTTY.rid, true);

    参数

    • rid: number
    • mode: boolean

    返回 void

shutdown

  • 不稳定:参数 how 和枚举 ShutdownMode 都在考虑移除。

    UNSTABLE*: Both the how parameter and ShutdownMode enum are under consideration for removal.

    Shutdown 套接字的发送和接收操作。

    Shutdown socket send and receive operations.

    与 POSIX 的 shutdown(3) 行为一致。

    Matches behavior of POSIX shutdown(3).

      const listener = Deno.listen({ port: 80 });
      const conn = await listener.accept();
      Deno.shutdown(conn.rid, Deno.ShutdownMode.Write);

    参数

    返回 void

signal

  • 不稳定: 新 API,没有经过审查。

    UNSTABLE*: new API, yet to be vetted.

    返回指定信号编码的流。返回值可用于异步迭代。

    Returns the stream of the given signal number. You can use it as an async iterator.

     for await (const _ of Deno.signal(Deno.Signal.SIGTERM)) {
       console.log("got SIGTERM!");
     }

    也可以把它作为 Promise 来使用。在这种情况下,只能收到第一个值。

    You can also use it as a promise. In this case you can only receive the first one.

     await Deno.signal(Deno.Signal.SIGTERM);
     console.log("SIGTERM received!")

    如果要停止接收信号,可以使用信号流对象(SignalStream)的 .dispose() 方法。

    If you want to stop receiving the signals, you can use .dispose() method of the signal stream object.

     const sig = Deno.signal(Deno.Signal.SIGTERM);
     setTimeout(() => { sig.dispose(); }, 5000);
     for await (const _ of sig) {
       console.log("SIGTERM!")
     }

    当调用 sig.dispose() 5 秒后,上述 for-await 循环退出。

    The above for-await loop exits after 5 seconds when sig.dispose() is called.

    注意: 这个功能还没有在 Windows 上实现。

    NOTE: This functionality is not yet implemented on Windows.

    参数

    • signo: number

    返回 SignalStream

stat

  • 解析给定 path,返回 Deno.FileInfo。如果 path 为符号链接,则返回符号链接指向的文件。

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

      const fileInfo = await Deno.stat("hello.txt");
      assert(fileInfo.isFile);

    需要 allow-read 权限。

    Requires allow-read permission.

    参数

    • path: string

    返回 Promise<FileInfo>

statSync

  • 同步方式解析给定 path,返回 Deno.FileInfo。 如果 path 为符号链接,则返回符号链接指向的文件。

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

      const fileInfo = Deno.statSync("hello.txt");
      assert(fileInfo.isFile);

    需要 allow-read 权限。

    Requires allow-read permission.

    参数

    • path: string

    返回 FileInfo

symlink

  • symlink(oldpath: string, newpath: string, type?: string): Promise<void>
  • 不稳定type 参数可能更改为 "dir" | "file" 的联合类型。

    UNSTABLE*: type argument may be changed to "dir" | "file"

    创建 newpath 作为指向 oldpath 的符号链接。

    Creates newpath as a symbolic link to oldpath.

    type 参数可以设置为 dirfile。此参数仅在 Windows 上可用,其他平台会被忽略。

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

    注意:此函数尚未在 Windows 上实现。

    NOTE: This function is not yet implemented on Windows.

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

    需要 allow-readallow-write 权限。

    Requires allow-read and allow-write permissions.

    参数

    • oldpath: string
    • newpath: string
    • Optional type: string

    返回 Promise<void>

symlinkSync

  • symlinkSync(oldpath: string, newpath: string, type?: string): void
  • 不稳定type 参数可能更改为 "dir" | "file" 的联合类型。

    UNSTABLE*: type argument type may be changed to "dir" | "file".

    同步方式创建 newpath 作为指向 oldpath 的符号链接。

    Creates newpath as a symbolic link to oldpath.

    type 参数可以设置为 dirfile。此参数仅在 Windows 上可用,其他平台会被忽略。

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

    注意:此函数尚未在 Windows 上实现。

    NOTE: This function is not yet implemented on Windows.

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

    需要 allow-readallow-write 权限。

    Requires allow-read and allow-write permissions.

    参数

    • oldpath: string
    • newpath: string
    • Optional type: string

    返回 void

test

  • test(t: TestDefinition): void
  • test(fn: () => void | Promise<void>): void
  • test(name: string, fn: () => void | Promise<void>): void
  • 注册一个测试,它将在命令行执行 deno test 操作并且包含的模块看起来像一个测试模块时运行, 或者在使用 Deno.runTests 时显式运行。如果需要, fn 可以是异步的。

    Register a test which will be run when deno test is used on the command line and the containing module looks like a test module, or explicitly when Deno.runTests is used. fn can be async if required.

         import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts";
         Deno.test({
           name: "example test",
           fn(): void {
             assertEquals("world", "world");
           },
         });
         Deno.test({
           name: "example ignored test",
           ignore: Deno.build.os === "win"
           fn(): void {
             // 仅在 Windows 机器上忽略这个测试。
           },
         });
         Deno.test({
           name: "example async test",
           async fn() {
             const decoder = new TextDecoder("utf-8");
             const data = await Deno.readFile("hello_world.txt");
             assertEquals(decoder.decode(data), "Hello world")
           }
         });

    参数

    返回 void

  • 注册一个测试,它将在命令行执行 deno test 操作并且包含的模块看起来像一个测试模块时运行, 或者在使用 Deno.runTests 时显式运行。

    Register a test which will be run when deno test is used on the command line and the containing module looks like a test module, or explicitly when Deno.runTests is used

       import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts";
       Deno.test(function myTestFunction():void {
         assertEquals("hello", "hello");
       });
       Deno.test(async function myAsyncTestFunction():Promise<void> {
         const decoder = new TextDecoder("utf-8");
         const data = await Deno.readFile("hello_world.txt");
         assertEquals(decoder.decode(data), "Hello world")
       });

    参数

    • fn: () => void | Promise<void>
        • (): void | Promise<void>
        • 返回 void | Promise<void>

    返回 void

  • 注册一个测试,它将在命令行执行 deno test 操作并且包含的模块看起来像一个测试模块时运行, 或者在使用 Deno.runTests 时显式运行。

    Register a test which will be run when deno test is used on the command line and the containing module looks like a test module, or explicitly when Deno.runTests is used

       import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts";
       Deno.test("My test description", ():void => {
         assertEquals("hello", "hello");
       });
       Deno.test("My async test description", async ():Promise<void> => {
         const decoder = new TextDecoder("utf-8");
         const data = await Deno.readFile("hello_world.txt");
         assertEquals(decoder.decode(data), "Hello world")
       });

    参数

    • name: string
    • fn: () => void | Promise<void>
        • (): void | Promise<void>
        • 返回 void | Promise<void>

    返回 void

toAsyncIterator

  • toAsyncIterator(r: Reader): AsyncIterableIterator<Uint8Array>
  • 将 Reader 对象 (r) 转换为异步迭代器。

    Turns a Reader, r, into an async iterator.

     for await (const chunk of toAsyncIterator(reader)) {
       console.log(chunk);
     }

    参数

    返回 AsyncIterableIterator<Uint8Array>

transpileOnly

  • 不稳定:新的 API,尚待审核。

    UNSTABLE*: new API, yet to be vetted.

    给定一组 TypeScript 类型的源码 (sources),返回解析后的映射, 其中的 key 是 sources 的 key,结果则包含转化过的源码及源码的 source map。 此函数并不进行类型校检,它可以有效地从文件中 “删除” 类型。

    Takes a set of TypeScript sources and resolves to a map where the key was the original file name provided in sources and the result contains the source and optionally the map from the transpile operation. This does no type checking and validation, it effectively "strips" the types from the file.

     const results =  await Deno.transpileOnly({
       "foo.ts": `const foo: string = "foo";`
     });

    参数

    • sources: Record<string, string>

      key 是文件名,value 是要转换的源码。 文件扩展名并不会被解析,仅用作解析结果的 key。

      A map where the key is the filename and the value is the text to transpile. The filename is only used in the transpile and not resolved, for example to fill in the source name in the source map.

    • Optional options: CompilerOptions

      编译选项。这是可以被 Deno 支持的 ts.CompilerOptions 选项的一个子集。

      An option object of options to send to the compiler. This is a subset of ts.CompilerOptions which can be supported by Deno. Many of the options related to type checking and emitting type declaration files will have no impact on the output.

    返回 Promise<Record<string, TranspileOnlyResult>>

truncate

  • truncate(name: string, len?: number): Promise<void>
  • 通过指定的 len ,截取或者扩展指定的文件内容。如果未指定 len ,则整个文件内容将被截取。

    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.writeFile(file, new TextEncoder().encode("Hello World"));
      await Deno.truncate(file, 7);
      const data = await Deno.readFile(file);
      console.log(new TextDecoder().decode(data));  //"Hello W"

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

    • name: string
    • Optional len: number

    返回 Promise<void>

truncateSync

  • truncateSync(name: string, len?: number): void
  • 同步地通过指定的 len ,截取或者扩展指定的文件内容。如果未指定 len ,则整个文件内容将被截取。

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

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

    • name: string
    • Optional len: number

    返回 void

umask

  • umask(mask?: number): number
  • 不稳定: 新 API,没有经过审查。正在考虑调用此 API 时,是否需要申请权限。

    UNSTABLE: New API, yet to be vetted. This API is under consideration to determine if permissions are required to call it.

    获取进程权限掩码。如果提供 mask,则设置进程权限掩码。 此函数始终返回调用前的权限掩码。

    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)

    注意: 此 API 未在 Windows 平台实现。

    NOTE: This API is not implemented on Windows

    参数

    • Optional mask: number

    返回 number

utime

  • utime(path: string, atime: number | Date, mtime: number | Date): Promise<void>
  • UNSTABLE: 需要调研高精度的 time。

    UNSTABLE*: needs investigation into high precision time.

    基于文件系统的 path 改变访问 (atime) 和修改 (mtime) 的时间。 给定的时间以秒 (UNIX epoch time) 为单位或着是 Date 对象。

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

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

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

    返回 Promise<void>

utimeSync

  • utimeSync(path: string, atime: number | Date, mtime: number | Date): void
  • 不稳定:需要对高精度时间(hrtime)进行调查。

    UNSTABLE*: needs investigation into high precision time.

    同步地更改路径(path)引用的文件系统对象的访问时间(atime)和修改时间(mtime)。 给定的时间参数可以是秒(UNIX 纪元时间)或者日期对象。

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

    需要 allow-write 权限。

    Requires allow-write permission.

    参数

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

    返回 void

write

  • write(rid: number, data: Uint8Array): Promise<number>
  • 将数组缓冲区 (data) 的内容写入资源ID的所属文件 (rid) 。

    Write to the resource ID (rid) the contents of the array buffer (data).

    解析为写入的字节数。

    Resolves to the number of bytes written.

     const encoder = new TextEncoder();
     const data = encoder.encode("Hello world");
     const file = await Deno.open("/foo/bar.txt");
     const bytesWritten = await Deno.write(file.rid, data); // 11
     Deno.close(file.rid);

    参数

    • rid: number
    • data: Uint8Array

    返回 Promise<number>

writeAll

  • writeAll(w: Writer, arr: Uint8Array): Promise<void>
  • 将所有 Array Buffer (arr)中的的内容写入到对象 (w) 中。

    Write all the content of the array buffer (arr) to the writer (w).

      // 举例:写入到 stdout
      const contentBytes = new TextEncoder().encode("Hello World");
      await Deno.writeAll(Deno.stdout, contentBytes);
      // 举例:写入到文件
      const contentBytes = new TextEncoder().encode("Hello World");
      const file = await Deno.open('test.file', {write: true});
      await Deno.writeAll(file, contentBytes);
      Deno.close(file.rid);
      // 举例:写入到 Buffer 对象
      const contentBytes = new TextEncoder().encode("Hello World");
      const writer = new Deno.Buffer();
      await Deno.writeAll(writer, contentBytes);
      console.log(writer.bytes().length);  // 11

    参数

    返回 Promise<void>

writeAllSync

  • writeAllSync(w: WriterSync, arr: Uint8Array): void
  • 将所有 Array Buffer (arr)中的的内容同步写入到对象 (w) 中。

    Synchronously write all the content of the array buffer (arr) to the writer (w).

      // 举例:写入到 stdout
      const contentBytes = new TextEncoder().encode("Hello World");
      Deno.writeAllSync(Deno.stdout, contentBytes);
      // 举例:写入到文件
      const contentBytes = new TextEncoder().encode("Hello World");
      const file = Deno.openSync('test.file', {write: true});
      Deno.writeAllSync(file, contentBytes);
      Deno.close(file.rid);
      // 举例:写入到 Buffer 对象
      const contentBytes = new TextEncoder().encode("Hello World");
      const writer = new Deno.Buffer();
      Deno.writeAllSync(writer, contentBytes);
      console.log(writer.bytes().length);  // 11

    参数

    返回 void

writeFile

  • writeFile(path: string, data: Uint8Array, options?: WriteFileOptions): Promise<void>
  • data 写入给定的 path,并且根据需要创建新文件或者覆盖原文件。

    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);  // 覆盖或者创建 "hello1.txt"
      await Deno.writeFile("hello2.txt", data, {create: false});  // 仅当 "hello2.txt" 存在的情况下才有效
      await Deno.writeFile("hello3.txt", data, {mode: 0o777});  // 设置新文件的权限
      await Deno.writeFile("hello4.txt", data, {append: true});  // 在文件末尾添加数据

    需要 allow-write 权限。如果 options.createfalse 且需要 allow-read 权限。

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

    参数

    返回 Promise<void>

writeFileSync

  • writeFileSync(path: string, data: Uint8Array, options?: WriteFileOptions): void
  • 同步方式将 data 写入给定的 path,并且根据需要创建新文件或者覆盖原文件。

    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);  // 覆盖或者创建 "hello1.txt"
      Deno.writeFileSync("hello2.txt", data, {create: false});  // 仅当 "hello2.txt" 存在的情况下才有效
      Deno.writeFileSync("hello3.txt", data, {mode: 0o777});  // 设置新文件的权限
      Deno.writeFileSync("hello4.txt", data, {append: true});  // 在文件末尾添加数据

    需要 allow-write 权限。如果 options.createfalse 且需要 allow-read 权限。

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

    参数

    返回 void

writeSync

  • writeSync(rid: number, data: Uint8Array): number
  • 同步地将数组缓冲区 (data) 的内容写入资源ID的所属文件 (rid) 。

    Synchronously write to the resource ID (rid) the contents of the array buffer (data).

    返回写入的字节数。

    Returns the number of bytes written.

      const encoder = new TextEncoder();
      const data = encoder.encode("Hello world");
      const file = Deno.openSync("/foo/bar.txt");
      const bytesWritten = Deno.writeSync(file.rid, data); // 11
      Deno.close(file.rid);

    参数

    • rid: number
    • data: Uint8Array

    返回 number

图例说明

本文档使用 TypeDoc 生成。

Fork me on GitHub