Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass command line arguments to Deno?

I have a Deno app, that I wish to pass some command line args to. I searched the manual, but found nothing.

I tried to use the same commands used in Node.js, assuming they might be sharing some for the std libraries, but it didn't work as well.

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

Any suggestions?

like image 398
Ahmed Hammad Avatar asked May 16 '20 06:05

Ahmed Hammad


Video Answer


3 Answers

You can access arguments by using Deno.args, it will contain an array of the arguments passed to that script.

// deno run args.js one two three

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

If you want to parse those arguments you can use 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))

If you call it with:

deno run args.js -h 1 -w on

You'll get

{ _: [], h: 1, w: "on" }
like image 190
Marcos Casagrande Avatar answered Oct 19 '22 15:10

Marcos Casagrande


You can use Deno.args to access the command line arguments in Deno.

To try it create a file test.ts :

console.log(Deno.args);

And run it with deno run test.ts firstArgument secondArgument

It will return you with an array of the passed args:

$ deno run test.ts firstArgument secondArgument
[ "firstArgument", "secondArgument" ]
like image 39
BentoumiTech Avatar answered Oct 19 '22 16:10

BentoumiTech


If you take a stroll through the standard library, you will find a library named flags, which sounds like it could be library for command line parsing. In the README, you will find your answer in the very first line:

const { args } = Deno;

Also, if you look at 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), where you will also find your answer in the first line:

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

So, in short: the command line arguments are a property of the global Deno object, which is documented 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" ]

Note: According to the Manual, all non-web APIs are under the global Deno namespace.

like image 2
Jörg W Mittag Avatar answered Oct 19 '22 17:10

Jörg W Mittag