8

When working with NodeJS, I can pass the arguments to a Node script like this:

$ node node-server.js arg1 arg2=arg2-val arg3

And can get the arguments like so:

// print process.argv
process.argv.forEach(function (val, index, array) {
  console.log(index + ': ' + val);
});
//Output
0: node
1: /Users/umar/work/node/node-server.js
2: arg1 
3: arg2=arg2-val
4: arg3

How to get the command-line arguments in Deno?

Some experts suggested me to solve the problem by answers to the question

DevLoverUmar
  • 11,809
  • 11
  • 68
  • 98

2 Answers2

14

Deno executable path ~ process.argv[0]:

Deno.execPath()

File URL of executed script ~ process.argv[1]:

Deno.mainModule

You can use path.fromFileUrl for conversions of URL to path string:

import { fromFileUrl } from "https://deno.land/std@0.55.0/path/mod.ts";
const modPath = fromFileUrl(import.meta.url)

Command-line arguments ~ process.argv.slice(2):

Deno.args

Example

deno run --allow-read test.ts -foo -bar=baz 42

Sample output (Windows):

Deno.execPath(): <scoop path>\apps\deno\current\deno.exe
import.meta.url: file:///C:/path/to/project/test.ts
  as path: C:\path\to\project\test.ts
Deno.args: [ "-foo", "-bar=baz", "42" ]
callum
  • 34,206
  • 35
  • 106
  • 163
ford04
  • 66,267
  • 20
  • 199
  • 171
  • This is wrong. You can't use `import.meta.url` for this, it contains the current file (like `__filename` in Node), not the main file, unless they happen to be the same. – callum Jul 04 '21 at 09:54
  • 1
    `Deno.mainModule` is now stable. See [comparison](https://deno.land/manual/examples/module_metadata) with `import.meta.url`. – callum Jul 04 '21 at 10:16
  • @callum huh, this is exactly, what I have written? "// put this in your main file to get its full path" – ford04 Jul 07 '21 at 09:13
  • ok but it's under a heading `File URL of executed script ~ process.argv[1]` and introduced as an alternative to `Deno.mainModule` in that context. Anyway as `Deno.mainModule` is long stable now, it can be edited – callum Aug 16 '21 at 19:37
2

To get your script’s CLI arguments in Deno, just use Deno.args:

> deno run ./code.ts foo bar
console.log(Deno.args); // ['foo', 'bar']

If you need something identical to Node's process.argv for compatibility reasons, use the official 'node' shim:

import process from 'https://deno.land/std@0.120.0/node/process.ts'

console.log(process.argv); // ['/path/to/deno', '/path/to/code.ts', 'foo', 'bar']

For illustrative purposes, if you wanted to manually construct a process.argv-style array (without using the official 'node' shim) you could do this:

import { fromFileUrl } from "https://deno.land/std@0.120.0/path/mod.ts";

const argv = [
   Deno.execPath(),
   fromFileUrl(Deno.mainModule),
   ...Deno.args,
]

console.log(argv); // ['/path/to/deno', '/path/to/code.ts', 'foo', 'bar']
TehBrian
  • 3
  • 4
callum
  • 34,206
  • 35
  • 106
  • 163