How to add parameter in nodejs

Asked

Viewed 1,833 times

0

am beginner in dev and would like to know how to pass a parameter via function. For example:

function hello(name) {
     console.log("hello " + name);
}
hello("Fulano");

If I roll Node hello, he will return me "Hello So-and-so".

I would like to pass the parameter along with the function. That is, I want to run Node hello So-and-so and I want him to return me "Hello Fulano". How to proceed?

  • The parameters passed are in the object process.argv, take a look at him.. did not pass straight to Function, but you can read and call the Function

1 answer

1

Just use process.argv[2]. This property will store a read-only copy of the original value of argv[0] past when the arquivo.js was initiated.

function hello(name) {
     console.log("hello " + name);
}
hello( process.argv[2] );

Then you just run: node file.js Seu-Nome

To read other parameters, you can use the for, for example:

function hello(name) {
     console.log("hello " + name);
}

for (let i = 2; i < process.argv.length; i++) {
    hello( process.argv[i] );
}

Then you just run: node file.js Seu-Nome-1 Seu-Nome-2 Seu-Nome-3

  • 1

    process.argv.slice(2).forEach(nome => hello(nome)) looks cool also xD

  • @nbkhope also ^^

  • Thank you very much, guys.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.