What is the Deno equivalent of process.argv in Node.js?

Viewed 1332

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

2 Answers

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" ]

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 from 'https://deno.land/std@0.100.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.100.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']
Related