JavaScript Node.js Basics Handling Errors in Node Organizing Your Code with require

Przemyslaw Mazur
PRO
Przemyslaw Mazur
Pro Student 9,296 Points

Don't know how to pass two different arguments to the command line.

I have modified the get function to take two arguments. One of them is topic but when I type in node app.js chalkers JavaScript the app is reading the second argument as another user.

Here is a snapshot of my workspace https://w.trhou.se/8ydc2e87oh .

Please help.

2 Answers

Farid Wilhelm Zimmermann
Farid Wilhelm Zimmermann
16,727 Points

After you slice the process.argv array, you call users.forEach(profile.get). The forEach method is iterating over each of the members of your users array, passing its callback parameter (which is each element of your users array) to the profile.get function. That way you are invoking profile.get multiple times, which leads to multiple API calls in turn. For every time the forEach iterates over your users array, it only passes down 1 parameter to the profile.get function.

To fix this, you should do something like this.

const profile = require('./profile.js');

const users = process.argv.slice(2);
profile.get(users[0], users[1])

^ if you are expecting only two command line arguments

const profile = require('./profile.js');

const users = process.argv.slice(2);
for (let i = 0; i < users.length; i+= 2) {
  profile.get(users[i], users[i + 1])
}

^if you have an unknown number of users and topics you want to retrieve. However, this will lead to an error, if you are not passing in the proper number of command line arguments. Hope it was understandable!

David Soards
David Soards
18,313 Points

this is just what I was looking for. Thanks!

James Estrada
James Estrada
17,816 Points

You could also use destructuring and a for...of loop to go through each username for a particular topic, for example:

const profile = require('./profile.js');

//take the first element of the array as the topic and the rest as an array of usernames
let [topic, ...usernames] = process.argv.slice(2);
//go through each username and pass the same topic to each one of them as arguments to the get method
for (let username of usernames){
  profile.get(topic, username);
}

You can modify the above to add more topics and loop through each one of them as well.

Fabian Forsström
Fabian Forsström
7,969 Points

I like this answer! Thank you James :)