Recibir argumentos desde la consola

Node proporciona métodos para recibir banderas/parametros/opciones desde la consolola en nuestros programas _config.yml

Recibir argumentos desde la consola con nodejs

app.js

console.log(process.argv);
//Desestructuración de process.argv
//Argumento 3 si no viene se toma por defecto 'base=5'
const [ , , argv3 = 'base=5'] = process.argv;

console.log(argv3)

//Salida esperada si se llama a la app sin parametros en consola
//base = 5

node app --base=20
(property) NodeJS.Process.argv: string[]

The process.argv property returns an array containing the command-line arguments passed when the Node.js process was launched. The first element will be execPath. See process.argv0 if access to the original value of argv[0] is needed. The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command-line arguments.

For example, assuming the following script for process-args.js:

import { argv } from 'node:process';

// print process.argv
argv.forEach((val, index) => {
  console.log(`${index}: ${val}`);
});

Launching the Node.js process as:

    node process-args.js one two=three four

Would generate the output:

  • 0: /usr/local/bin/node
  • 1: /Users/mjr/work/node/process-args.js
  • 2: one
  • 3: two=three
  • 4: four

@since — v0.1.27

Written on September 24, 2023