Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Node.js Basics 2017 Building a Command Line Application Capturing Command Line Arguments

Why in the video when we use const users = process.argv.slice(2) we don't need the line const username = ['chalkers',~~]

The note I am taking from the video

//make the application flexible

//wrap the code in a function get Profile function getProfile(username) { // Connect to the API URL (https://teamtreehouse.com/username.json) const request = https.get(https://teamtreehouse.com/${username}.json, response => { let body = ""; // Read the data response.on('data', data => { body += data.toString(); });

response.on('end', () => { // Parse the data const profile = JSON.parse(body);
// Print the data printMessage(username, profile.badges.length, profile.points.JavaScript); }); }); }

// const username = ['chalkers','alenaholligan', 'dave']; // getProfile('chalkers'); // getProfile('alenaholligan');

                    //slice here from the 3rd number in an array, we don't want the first 2

const users = process.argv.slice(2); //command line like node app.js chalker alena dave to check data users.forEach(getProfile); //shorten //users.forEach(usernmae => { getProfile(usernmae); }

Henry Blandon
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Henry Blandon
Full Stack JavaScript Techdegree Graduate 21,485 Points

Hanwen Zhang, The process.argv property returns an array containing the command-line arguments passed when the Node.js process was launched. This mean you pass the user name information in the command-line, like so: node app.js chalkers alenaholligan dave. in addition of the names you pass, it will return two more element in the array index 0 and index 1, you do no want the first two, therefore you slide them. if you try console.log(process.argv) you should be able to see the first two elements I am talking about.

1 Answer

Hi Hanwen,

I’m not 100% sure that I understand your question, but if you’re wondering why you use the slice method, it’s because argv will return the following array:

[‘node’, ‘app.js’, ‘chalker’, ‘alena’, ‘dave’].

It returns every string that makes up the command, but you only want to pass the final three into the for loop.

Does that answer your question?