如何将命令行参数传递给 Deno?

How to pass command line arguments to Deno?

我有一个 Deno app, that I wish to pass some command line args to. I searched the manual,但什么也没找到。

我尝试使用在 Node.js 中使用的相同命令,假设他们可能正在为标准库共享一些命令,但效果不佳。

var args = process.argv.slice(2); 
// Uncaught ReferenceError: process is not defined

有什么建议吗?

您可以使用 Deno.args 访问 Deno 中的命令行参数。

要尝试创建一个文件 test.ts :

console.log(Deno.args);

和运行它与deno run test.ts firstArgument secondArgument

它会 return 为您提供一组传递的参数:

$ deno run test.ts firstArgument secondArgument
[ "firstArgument", "secondArgument" ]

如果您在 standard library, you will find a library named flags, which sounds like it could be library for command line parsing. In the README 中漫步,您会在第一行找到答案:

const { args } = Deno;

此外,如果您查看 the Deno Manual, specifically the Examples section, you will find numerous examples of command line example programs that perform argument parsing, for example, a clone of the Unix cat command (which is also included in the First Steps section of the Deno Manual),您也可以在第一行找到答案:

for (let i = 0; i < Deno.args.length; i++)

所以,简而言之:命令行参数是全局 Deno 对象的 属性,记录在案 here:

const Deno.args: string[]

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

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

Then Deno.args will contain:

[ "/etc/passwd" ]

注意:根据手册,所有非网络 API 都在全局 Deno 命名空间下。

您可以使用 Deno.args 访问参数,它将包含传递给该脚本的参数数组。

// deno run args.js one two three

console.log(Deno.args); // ['one, 'two', 'three']

如果你想解析这些参数,你可以使用 std/flags, which will parse the arguments similar to minimist

import { parse } from "https://deno.land/std/flags/mod.ts";

console.log(parse(Deno.args))

如果你调用它:

deno run args.js -h 1 -w on

你会得到

{ _: [], h: 1, w: "on" }