How to add parameter in nodejs

0

I'm new to 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 run node hello , it will return "Hello So-and-so."

However, 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 it to return me "Hello So-and-so." How to proceed?

    
asked by anonymous 15.03.2018 / 17:05

1 answer

1

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

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

Then just run: node file.js Seu-Nome

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

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

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

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

    
15.03.2018 / 17:11